#' Explore a dataset from a PCA perspective
#'
#' Launch a Shiny App for interactive exploration of a dataset from the perspective
#' of Principal Components Analysis
#'
#' @param dds A \code{\link{DESeqDataSet}} object. If not provided, then a \code{countmatrix}
#' and a \code{coldata} need to be provided. If none of the above is provided, it is possible
#' to upload the data during the execution of the Shiny App
#' @param dst A \code{\link{DESeqTransform}} object. Can be computed from the \code{dds} object
#' if left NULL. If none is provided, then a \code{countmatrix}
#' and a \code{coldata} need to be provided. If none of the above is provided, it is possible
#' to upload the data during the execution of the Shiny App
#' @param countmatrix A count matrix, with genes as rows and samples as columns. If not provided, it is possible
#' to upload the data during the execution of the Shiny App
#' @param coldata A data.frame containing the info on the covariates of each sample. If not provided, it is possible
#' to upload the data during the execution of the Shiny App
#' @param pca2go An object generated by the \code{\link{pca2go}} function, which contains
#' the information on enriched functional categories in the genes that show the top or bottom loadings
#' in each principal component of interest. If not provided, it is possible
#' to compute live during the execution of the Shiny App
#' @param annotation A \code{data.frame} object, with row.names as gene identifiers (e.g. ENSEMBL ids)
#' and a column, \code{gene_name}, containing e.g. HGNC-based gene symbols
#' @param runLocal A logical indicating whether the app is to be run locally or remotely on a server, which determines how documentation will be accessed.
#'
#' @return A Shiny App is launched for interactive data exploration
#'
#' @examples
#' library(airway)
#' data(airway)
#' airway
#' dds_airway <- DESeq2::DESeqDataSetFromMatrix(assay(airway),
#'                                              colData = colData(airway),
#'                                              design = ~dex+cell)
#' \dontrun{
#' rld_airway <- DESeq2::rlogTransformation(dds_airway)
#'
#' pcaExplorer(dds_airway, rld_airway)
#'
#' pcaExplorer(countmatrix = counts(dds_airway), coldata = colData(dds_airway))
#'
#' pcaExplorer() # and then upload count matrix, covariate matrix (and eventual annotation)
#' }
#'
#' @export
pcaExplorer <- function(dds = NULL,
                        dst = NULL,
                        countmatrix = NULL,
                        coldata = NULL,
                        pca2go = NULL,
                        annotation = NULL,
                        runLocal = TRUE) {
  
  if (!requireNamespace("shiny", quietly = TRUE)) {
    stop("pcaExplorer requires 'shiny'. Please install it using
         install.packages('shiny')")
  }
  
  # get modes and themes for the ace editor
  modes <- shinyAce::getAceModes()
  themes <- shinyAce::getAceThemes()
  
  # create environment for storing inputs and values
  ## i need the assignment like this to export it up one level - i.e. "globally"
  pcaexplorer_env <<- new.env(parent = emptyenv())
  
  ## upload max 300mb files - can be changed if necessary
  options(shiny.maxRequestSize = 300 * 1024^2)
  
  # ui definition -----------------------------------------------------------
  pcaexplorer_ui <- shinydashboard::dashboardPage(
    # header definition -----------------------------------------------------------
    dashboardHeader(
      title = paste0("pcaExplorer - Interactive exploration of Principal Components ",
                     "of Samples and Genes in RNA-seq data - version ",
                     packageVersion("pcaExplorer")),
      titleWidth = 900,
      
      # task menu for saving state to environment or binary data
      shinydashboard::dropdownMenu(
        type = "tasks", icon = icon("cog"), badgeStatus = NULL,
        headerText = "pcaExplorer task menu",
        notificationItem(
          text = actionButton("exit_and_save", "Exit pcaExplorer & save",
                              class = "btn_no_border",
                              onclick = "setTimeout(function(){window.close();}, 100); "),
          icon = icon("sign-out"), status = "primary"),
        menuItem(
          text = downloadButton("state_save_sc", "Save State as .RData"))
      )
    ),
    # sidebar definition -----------------------------------------------------------
    dashboardSidebar(
      width = 280,
      
      menuItem(
        "App settings",
        icon = icon("cogs"),
        startExpanded = TRUE,
        selectInput("pc_x", label = "x-axis PC: ", choices = 1:8, selected = 1),
        shinyBS::bsTooltip(
          "pc_x", paste0("Select the principal component to display on the x axis"),
          "right", options = list(container = "body")),
        selectInput("pc_y", label = "y-axis PC: ", choices = 1:8, selected = 2),
        shinyBS::bsTooltip(
          "pc_y", paste0("Select the principal component to display on the y axis"),
          "right", options = list(container = "body")),
        uiOutput("color_by"),
        shinyBS::bsTooltip(
          "color_by", 
          paste0("Select the group of samples to stratify the analysis. Can also assume multiple values"),
          "right", options = list(container = "body")),
        numericInput("pca_nrgenes", label = "Nr of (most variant) genes:", 
                     value = 300, min = 50, max = 20000),
        shinyBS::bsTooltip(
          "pca_nrgenes", paste0(
            "Number of genes to select for computing the principal components. The top n genes are",
            " selected ranked by their variance inter-samples"),
          "right", options = list(container = "body")),
        numericInput("pca_point_alpha", label = "Alpha: ", value = 1, min = 0, max = 1, step = 0.01),
        shinyBS::bsTooltip(
          "pca_point_alpha", 
          paste0("Color transparency for the plots. Can assume values from 0 (transparent) ",
                 "to 1 (opaque)"),
          "right", options = list(container = "body")),
        numericInput("pca_label_size", label = "Labels size: ", value = 2, min = 1, max = 8),
        shinyBS::bsTooltip(
          "pca_label_size", paste0("Size of the labels for the samples in the principal components plots. ",
                                   "This also controls the size of the gene labels in the Genes View panel."),
          "right", options = list(container = "body")),
        numericInput("pca_point_size", label = "Points size: ", value = 2, min = 1, max = 8),
        shinyBS::bsTooltip(
          "pca_point_size", paste0("Size of the points to be plotted in the principal components plots"),
          "right", options = list(container = "body")),
        numericInput("pca_varname_size", label = "Variable name size: ", value = 4, min = 1, max = 8),
        shinyBS::bsTooltip(
          "pca_varname_size", paste0("Size of the labels for the genes PCA - correspond to the samples names"),
          "right", options = list(container = "body")),
        numericInput("pca_scale_arrow", label = "Scaling factor : ", value = 1, min = 0.01, max = 10),
        shinyBS::bsTooltip(
          "pca_scale_arrow", paste0("Scale value for resizing the arrow corresponding to the variables in the ",
                                    "PCA for the genes. It should be used for mere visualization purposes"),
          "right", options = list(container = "body")),
        selectInput("col_palette", "Color palette", choices = list("hue", "set1", "rainbow")),
        selectInput("plot_style", "Plot style for gene counts", choices = list("boxplot", "violin plot")),
        shinyBS::bsTooltip(
          "col_palette", paste0("Select the color palette to be used in the principal components plots. The number of ",
                                "colors is selected automatically according to the number of samples and to the levels ",
                                "of the factors of interest and their interactions"),
          "right", options = list(container = "body"))
      ), # end of menuItem
      menuItem(
        "Plot export settings", 
        icon = icon("paint-brush"),
        startExpanded = TRUE,
        
        numericInput("export_width",
                     label = "Width of exported figures (cm)", value = 10, min = 2),
        shinyBS::bsTooltip(
          "export_width", paste0("Width of the figures to export, expressed in cm"),
          "right", options = list(container = "body")),
        numericInput("export_height", label = "Height of exported figures (cm)", value = 10, min = 2),
        shinyBS::bsTooltip(
          "export_height", paste0("Height of the figures to export, expressed in cm"),
          "right", options = list(container = "body"))
      ) # end of menuItem
    ),
    
    # body definition ---------------------------------------------------------
    dashboardBody(
      ## Define output size and style of error messages
      tags$head(
        tags$style(HTML("
                        .shiny-output-error-validation {
                        font-size: 15px;
                        color: forestgreen;
                        text-align: center;
                        }
                        ")
        )
      ),
      
      # ui main tabBox -------------------------------------------------------
      tabBox(
        width = 12,
        # ui panel data upload -------------------------------------------------------
        tabPanel(
          "Data Upload", icon = icon("upload"),
          fluidRow(
            column(
              width = 4,
              uiOutput("upload_count_matrix"),
              shinyBS::bsTooltip(
                "upload_count_matrix", paste0("Select the file containing the count matrix"),
                "right", options = list(container = "body"))),
            column(
              width = 4,
              uiOutput("upload_metadata"),
              shinyBS::bsTooltip(
                "upload_metadata", paste0("Select the file containing the samples metadata"),
                "right", options = list(container = "body"))),
            column(
              width = 3,
              # help button?
              br(), br(), br(),
              uiOutput("ui_createDDS"),
              actionButton("help_format", label = "", icon = icon("question-circle"),
                           style = "color: #0092AC; background-color: #FFFFFF; border-color: #FFFFFF"),
              shinyBS::bsTooltip(
                "help_format", 
                "How to provide your input data in pcaExplorer",
                "bottom", options = list(container = "body"))
              #####              ,verbatimTextOutput("debugdebug")
            )),
          fluidRow(
            column(
              width = 4,
              uiOutput("upload_annotation"),
              shinyBS::bsTooltip(
                "upload_annotation", paste0("Select the file containing the annotation data"),
                "right", options = list(container = "body")),
              br(),
              "... or you can also ",
              actionButton("btn_loaddemo", "Load the demo airway data", 
                           icon = icon("play-circle"), style = "color: #0092AC"),
              # class = "btn btn-info"),
              shinyBS::bsTooltip(
                "btn_loaddemo", paste0("Clicking on this button will load the airway data as DESeqDataSet, apply the regularized log transformation, and prepare the annotation for displaying gene symbols"),
                "bottom", options = list(container = "body"))
            )
          )
          ,
          br(),
          p(),
          uiOutput("ui_computetransform"),
          
          h4("Preview on the available data"),
          fluidRow(
            column(
              width = 10,
              splitLayout(
                uiOutput("ui_showcm"),
                uiOutput("ui_showmetadata"),
                uiOutput("ui_showdds"),
                uiOutput("ui_showannotation")
              )
            )
          )
        ),
        
        # ui panel instructions -------------------------------------------------------
        tabPanel(
          "Instructions",  icon = icon("info-circle"),
          fluidRow(
            column(
              width = 12,
              p("These buttons will open the fully rendered vignettes, either built locally or directly from the Bioconductor package page."),
              actionButton(
                "open_vignette_full", label = "Open the User Guide (main vignette)",
                icon = icon("book"),
                onclick = ifelse(runLocal, "",
                                 # Use web vignette, with varying paths depending on whether we're release or devel.
                                 sprintf("window.open('http://bioconductor.org/packages/%s/bioc/vignettes/pcaExplorer/inst/doc/pcaExplorer.html', '_blank')",
                                         ifelse(unlist(packageVersion("pcaExplorer"))[2] %% 2L == 0L, "release", "devel")
                                 )
                )
              ),
              actionButton(
                "open_vignette_quickstart", label = "Open the 'Up and running' vignette",
                icon = icon("rocket"),
                onclick = ifelse(runLocal, "",
                                 # Use web vignette, with varying paths depending on whether we're release or devel.
                                 sprintf("window.open('http://bioconductor.org/packages/%s/bioc/vignettes/pcaExplorer/inst/doc/upandrunning.html', '_blank')",
                                         ifelse(unlist(packageVersion("pcaExplorer"))[2] %% 2L == 0L, "release", "devel")
                                 )
                )
              ),
              br(), br(),
              p("Otherwise, you can click on the collapsible element below to display a quickstart guide."),
              shinyBS::bsCollapse(
                id = "help_fulluserguide", open = NULL, 
                shinyBS::bsCollapsePanel(
                  "Up and running with pcaExplorer",
                  includeMarkdown(system.file("extdata", "instructions_unr.md", package = "pcaExplorer"))
                )
              )
            )
          )
          
        ),
        # ui panel counts table -------------------------------------------------------
        tabPanel(
          "Counts Table",
          icon = icon("table"),
          conditionalPanel(
            condition = "!output.checkdds",
            h3("Counts table"),
            
            selectInput("countstable_unit", label = "Data scale in the table",
                        choices = list("Counts (raw)" = "raw_counts",
                                       "Counts (normalized)" = "normalized_counts",
                                       "Regularized logarithm transformed" = "rlog_counts",
                                       "Log10 (pseudocount of 1 added)" = "log10_counts",
                                       "TPM (Transcripts Per Million)" = "tpm_counts")),
            
            DT::dataTableOutput("showcountmat"),
            
            downloadButton("downloadData", "Download", class = "btn btn-success"),
            hr(),
            h3("Sample to sample scatter plots"),
            selectInput("corr_method", "Correlation method palette",
                        choices = list("pearson", "spearman", "kendall")),
            checkboxInput(inputId = "corr_uselogs", label = "Use log2 values for plot axes and values",
                          value = TRUE),
            checkboxInput(inputId = "corr_usesubset", label = "Use a subset of max 1000 genes (quicker to plot)",
                          value = TRUE),
            
            p("Compute sample to sample correlations on the normalized counts - warning, it can take a while to plot all points (depending mostly on the number of samples you provided)."),
            actionButton("compute_pairwisecorr", "Run", class = "btn btn-primary"),
            uiOutput("pairwise_plotUI"),
            uiOutput("heatcorr_plotUI")
          ),
          conditionalPanel(
            condition = "output.checkdds",
            h2("You did not create the dds object yet. Please go the main tab and generate it"))
        ),
        # ui panel data overview -------------------------------------------------------
        tabPanel(
          "Data Overview", icon = icon("eye"),
          conditionalPanel(
            condition = "!output.checkrlt",
            h1("Sneak peek in the data"),
            h3("Design metadata"),
            DT::dataTableOutput("showcoldata"),
            
            h3("Sample to sample distance heatmap"),
            fluidRow(
              column(
                width = 8,
                selectInput(inputId = "sampledist_distance", label = "Select the distance method to use:",
                            choices = 
                              c(Euclidean="euclidean", Manhattan = "manhattan", `Correlation-based` = "cor"),
                            selected = "euclidean"),
                plotOutput("heatmapsampledist"),
                div(align = "right", style = "margin-right:15px; margin-bottom:10px",
                    downloadButton("download_samplessamplesheat", "Download Plot"),
                    textInput("filename_samplessamplesheat", label = "Save as...", value = "pcae_sampletosample.pdf")))
            ),
            hr(),
            h3("General information on the provided SummarizedExperiment/DESeqDataSet"),
            shiny::verbatimTextOutput("showdata"),
            h3("Number of million of reads per sample"),
            fluidRow(
              column(
                width = 8,
                plotOutput("reads_barplot"),
                div(align = "right", style = "margin-right:15px; margin-bottom:10px",
                    downloadButton("download_readsbarplot", "Download Plot"),
                    textInput("filename_readsbarplot", label = "Save as...", value = "pcae_readsbarplot.pdf")))),
            h3("Basic summary for the counts"),
            p("Number of uniquely aligned reads assigned to each sample"),
            verbatimTextOutput("reads_summary"),
            wellPanel(
              fluidRow(
                column(
                  width = 4,
                  numericInput("threshold_rowsums", "Threshold on the row sums of the counts", value = 0, min = 0)),
                column(
                  width = 4,
                  numericInput("threshold_rowmeans", "Threshold on the row means of the normalized counts", value = 0, min = 0))
              )),
            p("According to the selected filtering criteria, this is an overview on the provided count data"),
            verbatimTextOutput("detected_genes")),
          conditionalPanel(
            condition = "output.checkrlt",
            h2("You did not create the dst object yet. Please go the main tab and generate it")
          )
        ),
        # ui panel samples view -------------------------------------------------------
        tabPanel(
          "Samples View",
          icon = icon("share-alt"),
          conditionalPanel(
            condition = "!output.checkrlt",
            
            p(h1("Principal Component Analysis on the samples"),
              "PCA projections of sample expression profiles onto any pair of components."),
            fluidRow(
              column(
                width = 4,
                wellPanel(checkboxInput("sample_labels", "Display sample labels", value = TRUE),
                          checkboxInput("pca_ellipse", "draw a confidence ellipse for each group", value = FALSE),
                          sliderInput("pca_cislider", "select the confidence interval level", min = 0, max = 1, value = 0.95)))),
            fluidRow(
              column(
                width = 6,
                plotOutput("samples_pca", brush = "pca_brush"),
                div(align = "right", style = "margin-right:15px; margin-bottom:10px",
                    downloadButton("download_samplesPca", "Download Plot"),
                    textInput("filename_samplesPca", label = "Save as...", value = "samplesPca.pdf"))
              ),
              column(
                width = 6,
                plotOutput("samples_scree"),
                div(align = "right", style = "margin-right:15px; margin-bottom:10px",
                    downloadButton("download_samplesScree", "Download Plot"),
                    textInput("filename_samplesScree", label = "Save as...", value = "samplesScree.pdf")),
                wellPanel(fluidRow(
                  column(
                    width = 6,
                    radioButtons("scree_type", "Scree plot type:",
                                 choices = list("Proportion of explained variance" = "pev",
                                                "Cumulative proportion of explained variance" = "cev"), "pev")
                  ),
                  column(
                    width = 6,
                    numericInput("scree_pcnr", "Number of PCs to display", value = 8, min = 2)
                  )
                ))
              )
            ),
            hr(),
            fluidRow(
              column(
                width = 6,
                plotOutput("samples_pca_zoom"),
                div(align = "right", style = "margin-right:15px; margin-bottom:10px",
                    downloadButton("download_samplesPcazoom", "Download Plot"),
                    textInput("filename_samplesPcazoom", label = "Save as...", value = "samplesPcazoom.pdf"))
              ),
              column(
                width = 6,
                numericInput("ntophiload", "Nr of genes to display (top & bottom)", value = 10, min = 1, max = 40),
                plotOutput("geneshiload"),
                div(align = "right", style = "margin-right:15px; margin-bottom:10px",
                    downloadButton("download_samplesPca_hiload", "Download Plot"),
                    textInput("filename_samplesPca_hiload", label = "Save as...", value = "pcae_hiload.pdf"))
              )
            ),
            hr(),
            fluidRow(
              column(
                width = 6,
                p(h4("Outlier Identification"), "Toggle which samples to remove - suspected to be considered as outliers"),
                uiOutput("ui_outliersamples"),
                plotOutput("samples_outliersremoved"),
                div(align = "right", style = "margin-right:15px; margin-bottom:10px",
                    downloadButton("download_samplesPca_sampleout", "Download Plot"),
                    textInput("filename_samplesPca_sampleout", label = "Save as...", value = "samplesPca_sampleout.pdf"))
              )
            ),
            fluidRow(
              column(
                width = 8,
                selectInput("pc_z", "Select the principal component to display on the z axis", choices = 1:8, selected = 3),
                scatterplotThreeOutput("pca3d")
              )
            )
          ),
          conditionalPanel(
            condition = "output.checkrlt",
            h2("You did not create the dst object yet. Please go the main tab and generate it"))
        ),
        # ui panel genes view -------------------------------------------------------
        tabPanel(
          "Genes View",
          icon = icon("yelp"),
          conditionalPanel(
            condition = "!output.checkrlt",
            
            p(h1("Principal Component Analysis on the genes"), "PCA projections of genes abundances onto any pair of components."),
            
            fluidRow(checkboxInput("variable_labels", "Display variable labels", value = TRUE)),
            fluidRow(
              checkboxInput("ylimZero_genes", "Set y axis limit to 0", value = TRUE)),
            
            fluidRow(
              column(
                width = 6,
                h4("Main Plot - interact!"),
                plotOutput("genes_biplot", brush = "pcagenes_brush", click = "pcagenes_click"),
                div(align = "right", style = "margin-right:15px; margin-bottom:10px",
                    downloadButton("download_genesPca", "Download Plot"),
                    textInput("filename_genesPca", label = "Save as...", value = "genesPca.pdf"))),
              column(
                width = 6,
                h4("Zoomed window"),
                plotOutput("genes_biplot_zoom", click = "pcagenes_zoom_click"),
                div(align = "right", style = "margin-right:15px; margin-bottom:10px",
                    downloadButton("download_genesZoom", "Download Plot"),
                    textInput("filename_genesZoom", label = "Save as...", value = "genesPca_zoomed.pdf")))
            ),
            
            fluidRow(
              column(
                width = 6,
                h4("Profile explorer"),
                
                checkboxInput("zprofile", "Display scaled expression values", value = TRUE),
                plotOutput("genes_profileexplorer"),
                div(align = "right", style = "margin-right:15px; margin-bottom:10px",
                    downloadButton("download_genesPca_profile", "Download Plot"),
                    textInput("filename_genesPca_profile", label = "Save as...", value = "genesPca_profile.pdf")
                )
              ),
              column(
                width = 6,
                h4("Boxplot of selected gene"),
                
                plotOutput("genes_biplot_boxplot"),
                div(align = "right", style = "margin-right:15px; margin-bottom:10px",
                    downloadButton("download_genesPca_countsplot", "Download Plot"),
                    textInput("filename_genesPca_countsplot", label = "Save as...", value = "genesPca_countsplot.pdf")))
            ),
            
            fluidRow(
              column(
                width = 6,
                h4("Zoomed heatmap"),
                plotOutput("heatzoom"),
                div(align = "right", style = "margin-right:15px; margin-bottom:10px",
                    downloadButton("download_genesHeatmap", "Download Plot"),
                    textInput("filename_genesHeatmap", label = "Save as...", value = "genesHeatmap.pdf"))),
              column(
                width = 6,
                h4("Zoomed interactive heatmap"),
                fluidRow(radioButtons("heatmap_colv", "Cluster samples", choices = list("Yes" = TRUE, "No" = FALSE), selected = TRUE)),
                fluidRow(plotlyOutput("heatzoomly")))),
            
            hr(),
            box(
              title = "Table export options", status = "primary", solidHeader = TRUE,
              collapsible = TRUE, collapsed = TRUE, width = 12,
              fluidRow(
                column(
                  width = 6,
                  h4("Points selected by brushing - clicking and dragging:"),
                  DT::dataTableOutput("pca_brush_out"),
                  downloadButton("downloadData_brush", "Download brushed points"),
                  textInput("brushedPoints_filename", "File name...")),
                column(
                  width = 6,
                  h4("Points selected by clicking:"),
                  DT::dataTableOutput("pca_click_out"),
                  downloadButton("downloadData_click", "Download clicked (or nearby) points")),
                textInput("clickedPoints_filename", "File name...")
              )
            )
          ),
          conditionalPanel(
            condition = "output.checkrlt",
            h2("You did not create the dst object yet. Please go the main tab and generate it"))
        ),
        # ui panel gene finder -------------------------------------------------------
        tabPanel(
          "Gene Finder",
          icon = icon("crosshairs"),
          conditionalPanel(
            condition = "!output.checkdds",
            p(h1("GeneFinder")),
            fluidRow(
              wellPanel(
                width = 5,
                textInput("genefinder", label = "Type in the name of the gene to search", value = NULL),
                shinyBS::bsTooltip(
                  "genefinder", paste0(
                    "Type in the name of the gene to search. If no annotation is ",
                    "provided, you need to use IDs that are the row names of the ",
                    "objects you are using - count matrix, SummarizedExperiments ",
                    "or similar. If an annotation is provided, that also contains ",
                    "gene symbols or similar, the gene finder tries to find the ",
                    "name and the ID, and it suggests if some characters are in a ",
                    "different case"),
                  "bottom", options = list(container = "body")),
                checkboxInput("ylimZero", "Set y axis limit to 0", value = TRUE),
                checkboxInput("addsamplelabels", "Annotate sample labels to the dots in the plot", value = TRUE)),
              
              verbatimTextOutput("searchresult"),
              verbatimTextOutput("debuggene"),
              
              column(
                width = 8,
                plotOutput("genefinder_plot"),
                div(align = "right", style = "margin-right:15px; margin-bottom:10px",
                    downloadButton("download_genefinder_countsplot", "Download Plot"),
                    textInput("filename_genefinder_countsplot", label = "Save as...", value = "pcae_genefinder.pdf"))),
              column(
                width = 4,
                DT::dataTableOutput("genefinder_table"),
                downloadButton("download_genefinder_countstable", "Download Table")
              )
            )
          ),
          conditionalPanel(
            condition = "output.checkdds",
            h2("You did not create the dds object yet. Please go the main tab and generate it")
          )
        ),
        # ui panel pca2go -------------------------------------------------------
        tabPanel(
          "PCA2GO",
          icon = icon("magic"),
          conditionalPanel(
            condition = "!output.checkrlt",
            
            h1("pca2go - Functional annotation of Principal Components"),
            h4("Functions enriched in the genes with high loadings on the selected principal components"),
            # verbatimTextOutput("enrichinfo"),
            wellPanel(column(
              width = 6,
              uiOutput("ui_selectspecies")
            ),
            column(
              width = 6,
              uiOutput("ui_inputtype")
            ),
            
            shinyBS::bsTooltip(
              "ui_selectspecies", 
              paste0("Select the species for the functional enrichment analysis, ",
                     "choosing among the ones currently supported by limma::goana. ",
                     "Alternatively, for other species, it can be possible to use one ",
                     "of the available annotation packages in Bioconductor, and pre-",
                     "computing the pca2go object in advance"),
              "bottom", options = list(container = "body")),
            verbatimTextOutput("speciespkg"),
            checkboxInput("compact_pca2go", "Display compact tables", value = FALSE),
            shinyBS::bsTooltip(
              "compact_pca2go", 
              paste0("Should I display all the columns? If the information content of the ",
                     "tables is somehow too much for the screen width, as it can be for ",
                     "objects generated by pca2go with the topGO routines, the app can ",
                     "display just an essential subset of the columns"),
              "bottom", options = list(container = "body")),
            
            uiOutput("ui_computePCA2GO"),
            shinyBS::bsTooltip(
              "ui_computePCA2GO", 
              paste0("Compute a pca2go object, using the limma::goana function, ",
                     "after selecting the species of the experiment under investigation"),
              "bottom", options = list(container = "body"))),
            
            fluidRow(
              column(width = 3),
              column(
                width = 6,
                DT::dataTableOutput("dt_pcver_pos")),
              column(width = 3)
            ),
            
            fluidRow(
              column(4,
                     DT::dataTableOutput("dt_pchor_neg")),
              column(4,
                     plotOutput("pca2go")),
              column(4,
                     DT::dataTableOutput("dt_pchor_pos"))
            ),
            fluidRow(
              column(width = 3),
              column(
                width = 6,
                DT::dataTableOutput("dt_pcver_neg")),
              column(width = 3)
            )
          ),
          conditionalPanel(
            condition = "output.checkrlt",
            h2("You did not create the dst object yet. Please go the main tab and generate it"))
        ),
        
        # ui panel multifactor exploration -----------------------------------------------------
        tabPanel(
          "Multifactor Exploration",
          icon = icon("th-large"),
          conditionalPanel(
            condition = "!output.checkrlt",
            h1("Multifactor exploration of datasets with 2 or more experimental factors"),
            
            verbatimTextOutput("intro_multifac"),
            
            wellPanel(fluidRow(
              column(
                width = 6,
                uiOutput("covar1")
              ),
              column(
                width = 6,
                uiOutput("covar2")
              )
            ),
            fluidRow(
              column(
                width = 6,
                uiOutput("c1levels")
              ),
              column(
                width = 6,
                uiOutput("c2levels")
              )
            ),
            fluidRow(
              column(
                width = 6,
                uiOutput("colnames1"),
                uiOutput("colnames2")
              )
            ),
            
            shinyBS::bsTooltip(
              "covar1", paste0("Select the first experimental factor"),
              "bottom", options = list(container = "body")),
            shinyBS::bsTooltip(
              "covar2", paste0("Select the second experimental factor"),
              "bottom", options = list(container = "body")),
            shinyBS::bsTooltip(
              "c1levels", paste0("For factor 1, select two levels to contrast"),
              "bottom", options = list(container = "body")),
            shinyBS::bsTooltip(
              "c2levels", paste0("For factor 2, select two or more levels to contrast"),
              "bottom", options = list(container = "body")),
            shinyBS::bsTooltip(
              "colnames1", paste0("Combine samples belonging to Factor1-Level1 samples for each level in Factor 2"),
              "bottom", options = list(container = "body")),
            shinyBS::bsTooltip(
              "colnames2", paste0("Combine samples belonging to Factor1-Level2 samples for each level in Factor 2"),
              "bottom", options = list(container = "body"))),
            
            actionButton("composemat", "Compose the matrix", icon = icon("spinner"), class = "btn btn-primary"),
            shinyBS::bsTooltip(
              "composemat", 
              paste0("Select first two different experimental factors, for example ",
                     "condition and tissue. For each factor, select two or more ",
                     "levels. The corresponding samples which can be used are then displayed ",
                     "in the select boxes. Select an equal number of samples for each of ",
                     "the levels in factor 1, and then click the button to compute the ",
                     "new matrix which will be used for the visualizations below"),
              "bottom", options = list(container = "body")),
            
            wellPanel(fluidRow(
              column(4,
                     selectInput("pc_x_multifac", label = "x-axis PC: ", choices = 1:8,
                                 selected = 1)
              ),
              column(4,
                     selectInput("pc_y_multifac", label = "y-axis PC: ", choices = 1:8,
                                 selected = 2)
              ))),
            
            # fluidRow(verbatimTextOutput("multifacdebug")),
            fluidRow(
              column(6,
                     plotOutput("pcamultifac", brush = "pcamultifac_brush")),
              column(6,
                     plotOutput("multifaczoom"))
            ),
            fluidRow(downloadButton("downloadData_brush_multifac", "Download brushed points"),
                     textInput("brushedPoints_filename_multifac", "File name..."),
                     DT::dataTableOutput("pcamultifac_out"))
          ),
          conditionalPanel(
            condition = "output.checkrlt",
            h2("You did not create the dst object yet. Please go the main tab and generate it")
          )
        ),
        # ui panel report editor -------------------------------------------------------
        tabPanel(
          "Report Editor",
          icon = icon("pencil"),
          
          h1("Report Editor"),
          fluidRow(
            column(
              width = 6,
              box(
                title = "markdown options", status = "primary", solidHeader = TRUE, collapsible = TRUE, collapsed = TRUE, width = 9,
                radioButtons("rmd_dl_format", label = "Choose Format:", c("HTML" = "html", "R Markdown" = "rmd"), inline = TRUE),
                textInput("report_title", "Title: "),
                textInput("report_author", "Author: "),
                radioButtons("report_toc", "Table of Contents", choices = list("Yes" = "true", "No" = "false")),
                radioButtons("report_ns", "Number sections", choices = list("Yes" = "true", "No" = "false")),
                selectInput("report_theme", "Theme", 
                            choices = list("Default" = "default", "Cerulean" = "cerulean",
                                           "Journal" = "journal", "Flatly" = "flatly",
                                           "Readable" = "readable", "Spacelab" = "spacelab",
                                           "United" = "united", "Cosmo" = "cosmo")),
                radioButtons("report_echo", "Echo the commands in the output", choices = list("Yes" = "TRUE", "No" = "FALSE")))),
            column(
              width = 6,
              box(
                title = "editor options", status = "primary", solidHeader = TRUE, collapsible = TRUE, collapsed = TRUE, width = 9,
                checkboxInput("enableAutocomplete", "Enable AutoComplete", TRUE),
                conditionalPanel(
                  "input.enableAutocomplete",
                  wellPanel(
                    checkboxInput("enableLiveCompletion", "Live auto completion", TRUE),
                    checkboxInput("enableRCompletion", "R code completion", TRUE)
                  )
                ),
                
                selectInput("mode", "Mode: ", choices = modes, selected = "markdown"),
                selectInput("theme", "Theme: ", choices = themes, selected = "solarized_light"))
            )
            # ,
            # column( # kept for debugging purposes!
            #   width = 6,
            #   verbatimTextOutput("loadedRmd")
            # )
          ),
          fluidRow(
            column(3,
                   actionButton("updatepreview_button", "Update report", class = "btn btn-primary"), p()
            ),
            column(3, downloadButton("saveRmd", "Generate & Save", class = "btn btn-success"))
          ),
          
          tabBox(
            width = NULL,
            id = "report_tabbox",
            tabPanel("Report preview",
                     icon = icon("file-text"),
                     htmlOutput("knitDoc")
            ),
            
            tabPanel("Edit report",
                     icon = icon("pencil-square-o"),
                     aceEditor("acereport_rmd", mode = "markdown", theme = "solarized_light", autoComplete = "live",
                               value = "_Initialization of the_ `pcaExplorer` _report generation..._",
                               placeholder = "You can enter some code and text in R Markdown format",
                               height = "800px"))
          )
        ),
        # ui panel about -------------------------------------------------------
        tabPanel(
          "About", icon = icon("institution"),
          includeMarkdown(system.file("extdata", "about.md", package = "pcaExplorer")),
          hr(),
          
          h4("Session Info"),
          verbatimTextOutput("sessioninfo")
        )
        
        #           tabPanel(
        #             "Session manager",
        #             ## will put here the things to save/restore the sessions
        #             p("something"),
        #           )
      ) # end of tabBox
      , footer()
    ), # end of dashboardBody
    skin = "blue"
  ) 
  
  # server definition -------------------------------------------------------
  #nocov start
  pcaexplorer_server <- shinyServer(function(input, output, session) {
    # server setup reactives --------------------------------------------------------
    ## placeholder for the figures to export
    exportPlots <- reactiveValues(
      samplessamples_heatmap = NULL,
      reads_barplot = NULL,
      
      samplesPca = NULL,
      samplesZoom = NULL,
      samplesScree = NULL,
      samplesHiload = NULL,
      samplesOutlier = NULL,
      
      genesPca = NULL,
      genesZoom = NULL,
      genesProfile = NULL,
      genesBoxplot = NULL,
      genesHeatmap = NULL,
      
      genefinder_countsplot = NULL
    )
    
    if (!is.null(dds)) {
      if (is.null(sizeFactors(dds))) {
        withProgress({
          dds <- estimateSizeFactors(dds)
        },
        message = "Calculating size factors...",
        detail = "Using the DESeq normalization method.")
      }
    }
    
    ## reactive values to use in the app
    values <- reactiveValues()
    values$mydds <- dds
    values$mydst <- dst
    values$mycountmatrix <- countmatrix
    values$mymetadata <- coldata
    values$mypca2go <- pca2go
    values$myannotation <- annotation
    
    user_settings <- reactiveValues(save_width = 15, save_height = 11)
    
    if (!is.null(dds)) {
      # if provided as dds, can fill in the count matrix and metadata
      values$mycountmatrix <- counts(dds)
      values$mymetadata <- colData(dds)
    }
    output$checkdds <- reactive({
      is.null(values$mydds)
    })
    output$checkrlt <- reactive({
      is.null(values$mydst)
    })
    
    outputOptions(output, "checkdds", suspendWhenHidden = FALSE)
    outputOptions(output, "checkrlt", suspendWhenHidden = FALSE)
    
    if (runLocal) {
      observeEvent(input$open_vignette_full, {
        path <- system.file("doc", "pcaExplorer.html", package = "pcaExplorer")
        if (path == "") {
          showNotification("This vignette (User Guide) has not been built on this system, please run pcaExplorer with runLocal=FALSE or install the package with the option to build the vignettes", type = "error")
        } else {
          browseURL(path)
        }
      })
      observeEvent(input$open_vignette_quickstart, {
        path <- system.file("doc", "upandrunning.html", package = "pcaExplorer")
        if (path == "") {
          showNotification("This vignette (Up and running) has not been built on this system, please run pcaExplorer with runLocal=FALSE or install the package with the option to build the vignettes", type = "error")
        } else {
          browseURL(path)
        }
      })
    }
    
    
    # server setup dataset --------------------------------------------------------
    if (!is.null(dds)) {
      if (!is(dds, "DESeqDataSet"))
        stop("dds must be a DESeqDataSet object. If it is a simple counts matrix, provide it to the countmatrix parameter!")
      
      if (is.null(sizeFactors(dds))) {
        withProgress({
          dds <- estimateSizeFactors(dds)
        },
        message = "Calculating size factors...",
        detail = "Using the DESeq normalization method.")
      }
    }
    if (!is.null(dst)) {
      if (!is(dst, "DESeqTransform"))
        stop("dds must be a DESeqTransform object")
    }
    
    output$ui_computetransform <- renderUI({
      if (is.null(values$mydds))
        return(NULL)
      tagList(
        h4("Select one of the following transformations for your count data:"),
        actionButton("btn_computevst",
                     HTML("Compute variance stabilized </br>transformed data from the <code>dds</code> object"),
                     class = "btn btn-primary", icon = icon("spinner")),
        actionButton("btn_computerlog",
                     HTML("Compute regularized logarithm </br>transformed data from the <code>dds</code> object"),
                     class = "btn btn-primary", icon = icon("spinner")),
        actionButton("btn_computeshiftedlog",
                     HTML("Compute log2 data (with pseudocount 1)</br> from the <code>dds</code> object"),
                     class = "btn btn-primary", icon = icon("spinner"))
      )
    })
    
    observeEvent(input$btn_computevst, {
      withProgress(message = "Computing the variance stabilized transformed data...",
                   detail = "This step can take a little while",
                   value = 0, {
                     values$mydst <- vst(values$mydds)
                     values$transformation_type <- "vst"
                   })
    })
    
    observeEvent(input$btn_computerlog, {
      withProgress(message = "Computing the rlog transformed data...",
                   detail = "This step can take a little while",
                   value = 0, {
                     values$mydst <- rlog(values$mydds)
                     values$transformation_type <- "rlog"
                   })
    })
    
    observeEvent(input$btn_computeshiftedlog,
                 {
                   withProgress(message = "Computing the log2 transformed data...",
                                detail = "This step can take a little while",
                                value = 0, {
                                  values$mydst <- normTransform(values$mydds)
                                  values$transformation_type <- "shiftedlog"
                                })
                 })
    
    
    # server renderUI elements --------------------------------------------------------
    output$color_by <- renderUI({
      if (is.null(values$mydds))
        return(NULL)
      poss_covars <- names(colData(values$mydds))
      selectInput("color_by", label = "Group/color by: ",
                  choices = c(NULL, poss_covars), selected = NULL, multiple = TRUE)
    })
    
    ## Render the UI element to upload the count matrix
    output$upload_count_matrix <- renderUI({
      if (!is.null(dds) | !is.null(countmatrix)) {
        NULL
      } else {
        return(
          tagList(
            wellPanel(
              fileInput(inputId = "uploadcmfile",
                        label = "Upload a count matrix file",
                        accept = c("text/csv", "text/comma-separated-values",
                                   "text/tab-separated-values", "text/plain",
                                   ".csv", ".tsv"), multiple = FALSE,
                        width = "80%"),
              radioButtons(inputId = "uploadcm_sep", 
                           label = "Separator",
                           choices = c(Comma = ",", Semicolon = ";", Tab = "\t"),
                           selected = "\t",
                           inline = TRUE)
            )
          )
        )
      }
    })
    
    readCountmatrix <- reactive({
      if (is.null(input$uploadcmfile))
        return(NULL)
      cm <- utils::read.delim(input$uploadcmfile$datapath, header = TRUE,
                              as.is = TRUE, sep = input$uploadcm_sep, quote = "",
                              row.names = 1, # https://github.com/federicomarini/pcaExplorer/issues/1
                              check.names = FALSE)
      return(cm)
    })
    
    output$upload_metadata <- renderUI({
      if (!is.null(dds) | !is.null(coldata)) {
        NULL
      } else {
        return(
          tagList(
            wellPanel(
              fileInput(inputId = "uploadmetadatafile",
                        label = "Upload a sample metadata matrix file",
                        accept = c("text/csv", "text/comma-separated-values",
                                   "text/tab-separated-values", "text/plain",
                                   ".csv", ".tsv"), multiple = FALSE,
                        width = "80%"), 
              radioButtons(inputId = "uploadmeta_sep", 
                           label = "Separator",
                           choices = c(Comma = ",", Semicolon = ";", Tab = "\t"),
                           selected = "\t",
                           inline = TRUE)
            )
          )
        )
      }
    })
    
    readMetadata <- reactive({
      if (is.null(input$uploadmetadatafile))
        return(NULL)
      coldata <- utils::read.delim(input$uploadmetadatafile$datapath, header = TRUE,
                                   as.is = TRUE, sep = input$uploadmeta_sep, quote = "",
                                   check.names = FALSE)
      return(coldata)
    })
    
    output$upload_annotation <- renderUI({
      if (!is.null(annotation)) {
        NULL
      } else {
        return(
          tagList(
            wellPanel(
              fileInput(inputId = "uploadannotationfile",
                        label = "Upload an annotation file (optional)",
                        accept = c("text/csv", "text/comma-separated-values",
                                   "text/tab-separated-values", "text/plain",
                                   ".csv", ".tsv"), multiple = FALSE,
                        width = "80%"),
              radioButtons(inputId = "uploadanno_sep", 
                           label = "Separator",
                           choices = c(Comma = ",", Semicolon = ";", Tab = "\t"),
                           selected = "\t",
                           inline = TRUE)
            )
          )
        )
      }
    })
    
    readAnnotation <- reactive({
      if (is.null(input$uploadannotationfile))
        return(NULL)
      annodata <- utils::read.delim(input$uploadannotationfile$datapath, header = TRUE,
                                    as.is = TRUE, sep = input$uploadanno_sep, quote = "",
                                    check.names = FALSE)
      return(annodata)
    })
    
    output$ui_showcm <- renderUI({
      shiny::validate(
        need(!is.null(values$mycountmatrix),
             "No count matrix provided, please upload it or pass it as a parameter"
        )
      )
      actionButton(inputId = "show_cm", label = HTML("Show </br>count matrix"), class = "btn btn-success")
    })
    
    output$ui_showmetadata <- renderUI({
      shiny::validate(
        need(!is.null(values$mymetadata),
             "No sample metadata provided, please upload it or pass it as a parameter"
        )
      )
      actionButton(inputId = "show_metadata", label = HTML("Show </br>sample metadata"), class = "btn btn-success")
    })
    
    output$ui_showdds <- renderUI({
      shiny::validate(
        need(!is.null(values$mydds),
             "No dds object provided or computed, please upload its components (count matrix and metadata) or pass it as a parameter"
        )
      )
      actionButton(inputId = "show_dds", label = HTML("Show </br><code>dds</code> object"), class = "btn btn-success")
    })
    
    output$ui_showannotation <- renderUI({
      shiny::validate(
        need(!is.null(values$myannotation),
             "No gene annotation provided, please upload it or pass it as a parameter"
        )
      )
      actionButton(inputId = "show_annotation", label =  HTML("Show </br>gene annotation"), class = "btn btn-success")
    })
    
    # output$ddsprint <- renderPrint({
    #   values$mydds
    # })
    
    observeEvent(input$show_cm, {
      showModal(modalDialog(
        title = "Preview - Count matrix",
        div(style = "display:block;overflow-y:auto; overflow-x:auto;",
            DT::renderDataTable(values$mycountmatrix)),
        easyClose = TRUE,
        footer = NULL,
        size = "l"
      ))
    })
    observeEvent(input$show_metadata, {
      showModal(modalDialog(
        title = "Preview - Sample metadata",
        div(style = "display:block;overflow-y:auto; overflow-x:auto;",
            DT::renderDataTable(as.data.frame(values$mymetadata))),
        easyClose = TRUE,
        footer = NULL,
        size = "l"
      ))
    })
    observeEvent(input$show_dds, {
      showModal(modalDialog(
        title = "Preview - dds object",
        renderPrint(values$mydds),
        easyClose = TRUE,
        footer = NULL
      ))
    })
    observeEvent(input$show_annotation, {
      showModal(modalDialog(
        title = "Preview - gene annotation",
        div(style = "display:block;overflow-y:auto; overflow-x:auto;",
            DT::renderDataTable(values$myannotation)),
        easyClose = TRUE,
        footer = NULL,
        size = "l"
      ))
    })
    
    output$ui_createDDS <- renderUI({
      if (is.null(values$mycountmatrix) | is.null(values$mymetadata))
        return(NULL)
      tagList(
        actionButton("button_diydds", label = HTML("Generate the dds and </br>dst objects"), class = "btn btn-success"),
        shinyBS::bsTooltip(
          "button_diydds", 
          paste0("This will create the dds object, normalize it using the DESeq method, and generate ",
                 "a DESeqTransform object, where variance stabilized values are stored by default."),
          "bottom", options = list(container = "body"))
      )
    })
    
    observeEvent(input$help_format, {
      showModal(modalDialog(
        title = "Format specifications for pcaExplorer",
        includeMarkdown(system.file("extdata", "datainput.md", package = "pcaExplorer")),
        h4("Example:"),
        tags$img(
          src = base64enc::dataURI(file = system.file("www", "help_dataformats.png", package = "pcaExplorer"), mime = "image/png"),
          width = 750
        ),
        easyClose = TRUE,
        footer = NULL,
        size = "l"
      ))
    })
    
    #####    output$debugdebug <- renderPrint({
    #####      print((ncol(values$mycountmatrix) == nrow(values$mymetadata)))
    #####    })
    
    observeEvent(input$button_diydds,
                 {
                   withProgress(message = "Computing the objects...", value = 0, {
                     if (ncol(values$mycountmatrix) == nrow(values$mymetadata)) {
                       values$mydds <- DESeqDataSetFromMatrix(countData = values$mycountmatrix,
                                                              colData = values$mymetadata,
                                                              design = ~1)
                       
                       incProgress(0.1, detail = "Computing size factors for normalization")
                       values$mydds <- estimateSizeFactors(values$mydds)
                       incProgress(0.1, detail = "Generating DESeqTransform")
                       values$mydst <- vst(values$mydds)
                       values$transformation_type <- "vst"
                       showNotification("All objects required for the next steps have been computed, good to go!",
                                        type = "message")
                       if (is.null(values$myannotation))
                         showNotification("You might want to provide a gene annotation object, it can help increase the readability of the remainder functions (gene symbols can be displayed instead of ENSEMBL/Entrez ids, ...).")
                     } else {
                       showNotification("You possibly uploaded/provided non matching count data and samples metadata, please inspect these objects in the preview modals below.",
                                        type = "warning")
                     }
                   })
                 }
                 
    )
    
    
    # as in http://stackoverflow.com/questions/29716868/r-shiny-how-to-get-an-reactive-data-frame-updated-each-time-pressing-an-actionb
    observeEvent(input$uploadcmfile,
                 {
                   values$mycountmatrix <- readCountmatrix()
                 })
    
    observeEvent(input$uploadmetadatafile,
                 {
                   values$mymetadata <- readMetadata()
                 })
    
    observeEvent(input$uploadannotationfile,
                 {
                   values$myannotation <- readAnnotation()
                 })
    
    # load the demo data
    observeEvent(input$btn_loaddemo, withProgress(
      message = "Loading demo data...",
      detail = "Generating DESeqDataSet", value = 0,
      {
        aw <- requireNamespace("airway", quietly = TRUE)
        if (aw) {
          data(airway, package = "airway", envir = environment())
          
          cm_airway <- assay(airway)
          ed_airway <- as.data.frame(colData(airway))
          
          values$mycountmatrix <- cm_airway
          values$mymetadata <- ed_airway
          
          # just to be sure, overwrite the annotation and the rest
          
          values$mydds <- DESeqDataSetFromMatrix(countData = values$mycountmatrix,
                                                 colData = values$mymetadata,
                                                 design = ~cell + dex)
          incProgress(0.1, detail = "Computing size factors for normalization")
          values$mydds <- estimateSizeFactors(values$mydds)
          incProgress(0.1, detail = "Generating DESeqTransform")
          values$mydst <- vst(values$mydds)
          values$transformation_type <- "vst"
          incProgress(0.7, detail = "Retrieving annotation")
          
          values$myannotation <- get_annotation_orgdb(values$mydds, "org.Hs.eg.db", "ENSEMBL")
          showNotification("All objects required for the next steps have been computed, good to go!",
                           type = "message")
        } else {
          showNotification("The 'airway' package is currently not installed. Please do so by executing BiocManager::install('airway') before launching pcaExplorer", type = "warning")
        }
      })
    )
    
    colSel <- reactive({
      # find out how many colors to generate: if no factor is selected, either
      # return all say steelblue or all different
      
      if (!is.null(input$color_by)) {
        expgroups <- as.data.frame(colData(values$mydst)[, input$color_by])
        expgroups <- interaction(expgroups)
      } else {
        expgroups <- factor(colnames(values$mydst))
        # return(rep("steelblue",ncol(values$mydst))) # to return all same
      }
      
      nrgroups <- length(levels(expgroups))
      
      if (input$col_palette == "hue"){
        return(hue_pal()(nrgroups))
      }
      # hue_pal()(ncol(values$mydst)/2) # or somewhat other way
      if (input$col_palette == "set1"){
        if (nrgroups <= 9) { # max color nr allowed for set1
          return(brewer_pal(palette = "Set1")(nrgroups))
        } else {
          return(hue_pal()(nrgroups)) # plus print message?
        }
      }
      # (ncol(values$mydst)/2) # or somewhat other way
      if (input$col_palette == "rainbow"){
        return(rainbow(nrgroups))
      }
    })
    
    output$sessioninfo <- renderPrint({
      sessionInfo()
    })
    
    output$showdata <- renderPrint({
      values$mydds
    })
    
    output$showcoldata <- DT::renderDataTable({
      totreads <- (colSums(counts(values$mydds)))
      df <- data.frame(
        colData(values$mydds),
        "Total number of reads" = totreads
      )
      
      datatable(df)
    })
    
    current_countmat <- reactive({
      if (input$countstable_unit == "raw_counts")
        return(counts(values$mydds, normalized = FALSE))
      if (input$countstable_unit == "normalized_counts")
        return(counts(values$mydds, normalized = TRUE))
      if (input$countstable_unit == "rlog_counts")
        return(assay(values$mydst))
      if (input$countstable_unit == "log10_counts")
        return(log10(1 + counts(values$mydds, normalized = TRUE)))
      if (input$countstable_unit == "tpm_counts")
        return(NULL) ## TODO!: assumes length of genes/exons as known, and is currently not required in the dds
    })
    
    output$showcountmat <- DT::renderDataTable({
      datatable(current_countmat())
    })
    
    output$downloadData <- downloadHandler(
      filename = function() {
        paste0(input$countstable_unit, "table.csv")
      },
      content = function(file) {
        write.csv(current_countmat(), file)
      }
    )
    
    output$download_genefinder_countstable <- downloadHandler(
      filename = function() {
        paste0("genefinder_pcaE_", "table.csv")
      },
      content = function(file) {
        
        anno_id <- rownames(values$mydst)
        anno_gene <- values$myannotation$gene_name
        
        if (is.null(input$color_by) & input$genefinder != "")
          return(NULL)
        if (is.null(input$color_by) & input$genefinder == "")
          return(NULL)
        if (input$genefinder == "")
          return(NULL)
        if (!input$genefinder %in% anno_gene & !input$genefinder %in% anno_id)
          return(NULL)
        
        if (input$genefinder %in% anno_id) {
          selectedGene <- rownames(values$mydst)[match(input$genefinder, rownames(values$mydst))]
          selectedGeneSymbol <- values$myannotation$gene_name[match(selectedGene, rownames(values$myannotation))]
        }
        if (input$genefinder %in% anno_gene) {
          selectedGeneSymbol <- values$myannotation$gene_name[which(values$myannotation$gene_name == input$genefinder)]
          if (length(selectedGeneSymbol) > 1) return(ggplot() + annotate("text", label = paste0("Type in a gene name/id of the following:\n", paste(selectedGene, collapse = ", ")), 0, 0) + theme_bw())
          selectedGene <- rownames(values$myannotation)[which(values$myannotation$gene_name == input$genefinder)]
        }
        genedata <- plotCounts(values$mydds, gene = selectedGene, intgroup = input$color_by, returnData = TRUE)
        genedata
        
        write.csv(genedata, file)
      }
    )
    
    output$corrplot <- renderPlot({
      if (input$compute_pairwisecorr)
        withProgress(
          message = "Generating the scatterplot matrix...",
          detail = "This operation can take a while to render all points",
          value = 0,
          {
            pair_corr(current_countmat(), method = input$corr_method, log = input$corr_uselogs,
                      use_subset = input$corr_usesubset)
          })
    })
    
    output$heatcorr <- renderPlot({
      if (input$compute_pairwisecorr)
        pheatmap(cor(current_countmat()))
    })
    
    output$pairwise_plotUI <- renderUI({
      shiny::validate(
        need(input$compute_pairwisecorr,
             "Click on the Run button to generate the scatterplot matrix")
      )
      plotOutput("corrplot", height = "1000px")
    })
    
    output$heatcorr_plotUI <- renderUI({
      shiny::validate(
        need(input$compute_pairwisecorr,
             "Click on the Run button to generate the heatmap")
      )
      plotOutput("heatcorr")
    })
    
    # overview on number of detected genes on different threshold types
    output$detected_genes <- renderPrint({
      t1 <- rowSums(counts(values$mydds))
      t2 <- rowMeans(counts(values$mydds, normalized = TRUE))
      
      thresh_rowsums <- input$threshold_rowsums
      thresh_rowmeans <- input$threshold_rowmeans
      abs_t1 <- sum(t1 > thresh_rowsums)
      rel_t1 <- 100 * mean(t1 > thresh_rowsums)
      abs_t2 <- sum(t2 > thresh_rowmeans)
      rel_t2 <- 100 * mean(t2 > thresh_rowmeans)
      
      cat("Number of detected genes:\n")
      # TODO: parametrize the thresholds
      cat(abs_t1, "genes have at least a sample with more than", thresh_rowsums, "counts\n")
      cat(paste0(round(rel_t1, 3), "%"), "of the", nrow(values$mydds),
          "genes have at least a sample with more than", thresh_rowsums, "counts\n")
      cat(abs_t2, "genes have more than", thresh_rowmeans, "counts (normalized) on average\n")
      cat(paste0(round(rel_t2, 3), "%"), "of the", nrow(values$mydds),
          "genes have more than", thresh_rowsums, "counts (normalized) on average\n")
      cat("Counts are ranging from", min(counts(values$mydds)), "to", max(counts(values$mydds)))
    })
    
    output$heatmapsampledist <- renderPlot({
      if(input$sampledist_distance == "euclidean") {
        mydistmat <- as.matrix(dist(t(assay(values$mydst))))
      } else if(input$sampledist_distance == "manhattan") {
        mydistmat <- as.matrix(dist(t(assay(values$mydst)), method = "manhattan"))
      } else {
        # corr based
        mydistmat <- as.matrix(1 - cor(assay(values$mydst)))
      }
      if (!is.null(input$color_by)) {
        expgroups <- as.data.frame(colData(values$mydst)[, input$color_by])
        # expgroups <- interaction(expgroups)
        rownames(expgroups) <- colnames(values$mydst)
        colnames(expgroups) <- input$color_by
        
        pheatmap(mydistmat, annotation_col = expgroups)
      } else {
        pheatmap(mydistmat)
      }
    })
    
    output$reads_barplot <- renderPlot({
      rr <- colSums(counts(values$mydds)) / 1e6
      if (is.null(names(rr)))
        names(rr) <- paste0("sample_", 1:length(rr))
      rrdf <- data.frame(Reads = rr, Sample = names(rr), stringsAsFactors = FALSE)
      if (!is.null(input$color_by)) {
        selGroups <- as.data.frame(colData(values$mydds)[input$color_by])
        rrdf$Group <- interaction(selGroups)
        p <- ggplot(rrdf, aes_string("Sample", weight = "Reads")) + geom_bar(aes_string(fill = "Group")) + theme_bw()
        p
      } else {
        p <- ggplot(rrdf, aes_string("Sample", weight = "Reads")) + geom_bar() + theme_bw()
        
        exportPlots$reads_barplot <- p
        p
      }
    })
    
    output$reads_summary <- renderPrint({
      print(colSums(counts(values$mydds)))
      summary(colSums(counts(values$mydds)) / 1e6)
    })
    
    # server samples view --------------------------------------------------------
    output$samples_pca <- renderPlot({
      res <- pcaplot(values$mydst, intgroup = input$color_by, ntop = input$pca_nrgenes,
                     pcX = as.integer(input$pc_x), pcY = as.integer(input$pc_y),
                     text_labels = input$sample_labels,
                     point_size = input$pca_point_size, title = "Samples PCA",
                     ellipse = input$pca_ellipse, ellipse.prob = input$pca_cislider)
      
      res <- res + theme_bw()
      exportPlots$samplesPca <- res
      res
    })
    
    output$samples_pca_zoom <- renderPlot({
      shiny::validate(
        need(!is.null(input$pca_brush),
             "Zoom in by brushing in the main plot panel above"
        )
      )
      # if(is.null(input$pca_brush))
      # return(ggplot() + annotate("text",label="zoom in by brushing",0,0) + theme_bw())
      res <- pcaplot(values$mydst, intgroup = input$color_by, ntop = input$pca_nrgenes,
                     pcX = as.integer(input$pc_x), pcY = as.integer(input$pc_y),
                     text_labels = input$sample_labels,
                     point_size = input$pca_point_size, title = "Samples PCA - zoom in",
                     ellipse = input$pca_ellipse, ellipse.prob = input$pca_cislider
      )
      res <- res +
        coord_cartesian(
          xlim = c(input$pca_brush$xmin, input$pca_brush$xmax),
          ylim = c(input$pca_brush$ymin, input$pca_brush$ymax))
      res <- res + theme_bw()
      exportPlots$samplesZoom <- res
      res
    })
    
    output$samples_scree <- renderPlot({
      rv <- rowVars(assay(values$mydst))
      select <- order(rv, decreasing = TRUE)[seq_len(min(input$pca_nrgenes, length(rv)))]
      pca <- prcomp(t(assay(values$mydst)[select, ]))
      
      res <- pcascree(pca, type = input$scree_type, pc_nr = input$scree_pcnr, title = "Scree plot for the samples PCA")
      res <- res + theme_bw()
      exportPlots$samplesScree <- res
      res
    })
    
    output$geneshiload <- renderPlot({
      rv <- rowVars(assay(values$mydst))
      select <- order(rv, decreasing = TRUE)[seq_len(min(input$pca_nrgenes, length(rv)))]
      pca <- prcomp(t(assay(values$mydst)[select, ]))
      
      par(mfrow = c(2,1))
      hi_loadings(pca, whichpc = as.integer(input$pc_x), topN = input$ntophiload, annotation = values$myannotation)
      hi_loadings(pca, whichpc = as.integer(input$pc_y), topN = input$ntophiload, annotation = values$myannotation)
      
    })
    
    output$ui_outliersamples <- renderUI({
      available_samples <- c("", colnames(values$mydst))
      
      selectInput("outlierselection", label = "Select which sample(s) to remove - suspected outliers", choices = available_samples, multiple = TRUE)
    })
    
    output$samples_outliersremoved <- renderPlot({
      
      shiny::validate(
        need(input$outlierselection != "",
             message = "Select at least one sample to plot the new PCA where the selection is removed")
      )
      
      currentrlt <- values$mydst
      allsamples <- colnames(currentrlt)
      
      outliersamples <- input$outlierselection
      currentrlt <- currentrlt[, setdiff(allsamples, outliersamples)]
      
      res <- pcaplot(currentrlt, intgroup = input$color_by, ntop = input$pca_nrgenes,
                     pcX = as.integer(input$pc_x), pcY = as.integer(input$pc_y),
                     text_labels = input$sample_labels,
                     point_size = input$pca_point_size, title = "Samples PCA",
                     ellipse = input$pca_ellipse, ellipse.prob = input$pca_cislider
      )
      res <- res + theme_bw()
      # exportPlots$samplesPca <- res
      exportPlots$samplesOutlier <- res
      res
    })
    
    output$pca3d <- renderScatterplotThree({
      pcaplot3d(
        values$mydst, intgroup = input$color_by, ntop = input$pca_nrgenes,
        pcX = as.integer(input$pc_x), pcY = as.integer(input$pc_y), pcZ = as.integer(input$pc_z))
    })
    
    # server genes view ---------------------------------------------------------------
    output$genes_biplot <- renderPlot({
      if (!is.null(input$color_by)) {
        expgroups <- as.data.frame(colData(values$mydst)[, input$color_by])
        expgroups <- interaction(expgroups)
        expgroups <- factor(expgroups, levels = unique(expgroups))
        
      } else {
        expgroups <- colnames(values$mydst)
      }
      colGroups <- colSel()[factor(expgroups)]
      
      res <- genespca(values$mydst,
                      ntop = input$pca_nrgenes,
                      choices = c(as.integer(input$pc_x), as.integer(input$pc_y)),
                      biplot = TRUE,
                      arrowColors = factor(colGroups, levels = unique(colGroups)),
                      groupNames = expgroups,
                      alpha=input$pca_point_alpha, coordEqual = FALSE, useRownamesAsLabels = FALSE, labels.size = input$pca_label_size,
                      point_size = input$pca_point_size, varname.size = input$pca_varname_size, scaleArrow = input$pca_scale_arrow, annotation = values$myannotation)
      exportPlots$genesPca <- res
      res
    })
    
    output$genes_biplot_zoom <- renderPlot({
      shiny::validate(
        need(
          !is.null(input$pcagenes_brush),
          "Zoom in by brushing in the main panel - this will also allow displaying the gene names"
        )
      )
      
      if (!is.null(input$color_by)) {
        expgroups <- as.data.frame(colData(values$mydst)[, input$color_by])
        expgroups <- interaction(expgroups)
        expgroups <- factor(expgroups, levels = unique(expgroups))
      } else {
        expgroups <- colnames(values$mydst)
      }
      colGroups <- colSel()[factor(expgroups)]
      
      res <- genespca(values$mydst,
                      ntop = input$pca_nrgenes,
                      choices = c(as.integer(input$pc_x), as.integer(input$pc_y)),
                      biplot = TRUE,
                      arrowColors = factor(colGroups, levels = unique(colGroups)),
                      groupNames = expgroups,
                      alpha = input$pca_point_alpha, coordEqual = FALSE,
                      var.axes = input$variable_labels, # workaround for a ggplot2 bug/missing thing: here details: https://github.com/hadley/ggplot2/issues/905
                      labels.size = input$pca_label_size, varname.size = input$pca_varname_size,
                      scaleArrow = input$pca_scale_arrow, point_size = input$pca_point_size, annotation = values$myannotation)
      
      res <- res +
        coord_cartesian(
          xlim = c(input$pcagenes_brush$xmin, input$pcagenes_brush$xmax),
          ylim = c(input$pcagenes_brush$ymin, input$pcagenes_brush$ymax))
      exportPlots$genesZoom <- res
      res
    })
    
    output$genes_profileexplorer <- renderPlot({
      shiny::validate(
        need(
          !is.null(input$pcagenes_brush),
          "Zoom in by brushing in the main panel"
        )
      )
      shiny::validate(
        need(
          length(input$color_by) > 0,
          "Select an experimental factor in the Group/color by element in the sidebar"
        )
      )
      geneprofiler(values$mydst,
                   genelist = curData_brush()$ids,
                   intgroup = input$color_by,
                   plotZ = input$zprofile)
    })
    
    output$genes_biplot_boxplot <- renderPlot({
      shiny::validate(
        need(
          length(input$color_by) > 0,
          "Select an experimental factor in the Group/color by element in the sidebar"
        )
      )
      shiny::validate(
        need(
          !is.null(input$pcagenes_zoom_click),
          "Click the plot above to generate the boxplot for the selected gene"
        )
      )
      selectedGene <- curData_zoomClick()$ids
      selectedGeneSymbol <- values$myannotation$gene_name[match(selectedGene, rownames(values$myannotation))]
      # plotCounts(dds_cleaner,)
      
      shiny::validate(
        need(nrow(curData_zoomClick()) > 0, message = "Click closer to a gene to get the boxplot")
        
      )
      
      genedata <- plotCounts(values$mydds, gene = selectedGene, intgroup = input$color_by, returnData = TRUE)
      
      onlyfactors <- genedata[, match(input$color_by, colnames(genedata))]
      genedata$plotby <- interaction(onlyfactors)
      
      genedata$sampleID <- rownames(genedata)
      
      # input$plot_style chooses the style of plotting
      if (input$plot_style == "boxplot") {
        res <- ggplot(genedata, aes_string(x = "plotby", y = "count", fill = "plotby")) +
          geom_boxplot(outlier.shape = NA, alpha=0.7) + theme_bw()
        if (input$ylimZero_genes) {
          res <- res + scale_y_log10(name = "Normalized counts - log10 scale", limits = c(0.4, NA))
        } else {
          res <- res + scale_y_log10(name = "Normalized counts - log10 scale")
        }
        
        res <- res +
          labs(title = paste0("Normalized counts for ", selectedGeneSymbol, " - ", selectedGene)) +
          scale_x_discrete(name = "") +
          geom_jitter(aes_string(x = "plotby", y = "count"), position = position_jitter(width = 0.1)) +
          scale_fill_discrete(name = "Experimental\nconditions")
        # if(input$addsamplelabels){
        #   res <- res + geom_text(aes(label=sampleID),hjust=-.1,vjust=0)
        # }
        
        exportPlots$genesBoxplot <- res
        res
      } else if (input$plot_style == "violin plot"){
        res <- ggplot(genedata, aes_string(x = "plotby", y = "count", fill = "plotby")) +
          geom_violin(aes_string(col = "plotby"), alpha = 0.6) + theme_bw()
        if (input$ylimZero_genes){
          res <- res + scale_y_log10(name = "Normalized counts - log10 scale", limits = c(0.4, NA))
        } else {
          res <- res + scale_y_log10(name = "Normalized counts - log10 scale")
        }
        
        res <- res +
          labs(title = paste0("Normalized counts for ", selectedGeneSymbol, " - ", selectedGene)) +
          scale_x_discrete(name = "") +
          geom_jitter(aes_string(x = "plotby", y = "count"), alpha = 0.8, position = position_jitter(width = 0.1)) +
          scale_fill_discrete(name = "Experimental\nconditions") + scale_color_discrete(guide = "none")
        # if(input$addsamplelabels){
        #   res <- res + geom_text(aes(label=sampleID),hjust=-.1,vjust=0)
        # }
        
        exportPlots$genesBoxplot <- res
        res
      }
    })
    
    # for reading in the brushed/clicked points
    curData_brush <- reactive({
      df2 <- genespca(values$mydst,
                      ntop = input$pca_nrgenes,
                      choices = c(as.integer(input$pc_x), as.integer(input$pc_y)),
                      biplot = TRUE,
                      # arrowColors = colGroups,
                      alpha = input$pca_point_alpha,
                      returnData = TRUE, annotation = values$myannotation)
      df2$geneName <- values$myannotation$gene_name[match(rownames(df2), rownames(values$myannotation))]
      res <- brushedPoints(df2, input$pcagenes_brush, xvar = "xvar", yvar = "yvar")
      res
    })
    
    curData_click <- reactive({
      df2 <- genespca(values$mydst,
                      ntop = input$pca_nrgenes,
                      choices = c(as.integer(input$pc_x), as.integer(input$pc_y)),
                      biplot = TRUE,
                      # arrowColors = colGroups,
                      alpha = input$pca_point_alpha,
                      returnData = TRUE, annotation = values$myannotation)
      df2$geneName <- values$myannotation$gene_name[match(rownames(df2), rownames(values$myannotation))]
      res <- nearPoints(df2, input$pcagenes_click,
                        threshold = 20, maxpoints = 3,
                        addDist = TRUE)
      res
    })
    
    # data to be used for plotting the picked gene from the zoomed panel
    curData_zoomClick <- reactive({
      df2 <- genespca(values$mydst,
                      ntop = input$pca_nrgenes,
                      choices = c(as.integer(input$pc_x), as.integer(input$pc_y)),
                      biplot = TRUE,
                      # arrowColors = colGroups,
                      alpha = input$pca_point_alpha,
                      returnData = TRUE, annotation = values$myannotation)
      df2$geneName <- values$myannotation$gene_name[match(rownames(df2), rownames(values$myannotation))]
      res <- nearPoints(df2, input$pcagenes_zoom_click,
                        threshold = 20, maxpoints = 1,
                        addDist = TRUE)
      res
    })
    
    output$pca_brush_out <- DT::renderDataTable({
      datatable(curData_brush(), options = list(pageLength = 50))
    })
    
    output$pca_click_out <- DT::renderDataTable({
      datatable(curData_click(), options = list(pageLength = 50))
    })
    
    output$heatzoomly <- renderPlotly({
      shiny::validate(
        need(
          !is.null(input$pcagenes_brush),
          "Brush the main panel above to generate a heatmap"
        )
      )
      brushedObject <- curData_brush()
      shiny::validate(
        need(
          nrow(brushedObject) > 1,
          "Brush to include at least two genes"
        )
      )
      
      selectedGenes <- brushedObject$ids
      toplot <- assay(values$mydst)[selectedGenes, ]
      rownames(toplot) <- values$myannotation$gene_name[match(rownames(toplot), rownames(values$myannotation))]
      
      mycolss <- c("#313695", "#4575b4", "#74add1", "#abd9e9", "#e0f3f8", "#fee090", "#fdae61", "#f46d43", "#d73027", "#a50026") # to be consistent with red/blue usual coding
      
      heatmaply(toplot, Colv = as.logical(input$heatmap_colv), colors = mycolss)
    })
    
    output$heatzoom <- renderPlot({
      shiny::validate(
        need(
          !is.null(input$pcagenes_brush),
          "Brush the main panel above to generate a heatmap"
        )
      )
      
      brushedObject <- curData_brush()
      shiny::validate(
        need(
          nrow(brushedObject) > 1,
          "Brush to include at least two genes"
        )
      )
      selectedGenes <- brushedObject$ids
      toplot <- assay(values$mydst)[selectedGenes, ]
      rownames(toplot) <- values$myannotation$gene_name[match(rownames(toplot), rownames(values$myannotation))]
      # pheatmap(toplot,cluster_cols = as.logical(input$heatmap_colv))
      NMF::aheatmap(toplot, Colv = as.logical(input$heatmap_colv))
      ## aheatmap is actually consistent in displaying the clusters with most of other heatmap packages
      ## keep in mind: pheatmap does somehow a better job if scaling/centering
    })
    
    # server gene finder ---------------------------------------------------------------
    output$searchresult <- renderPrint({
      if (is.null(input$color_by)) return("Select a factor to plot your gene")
      if (input$genefinder == "")
        return("Type in the gene name/id you want to plot")
      
      foundGeneID <- input$genefinder %in% rownames(values$mydst)
      foundGeneName <- input$genefinder %in% values$myannotation$gene_name
      if (!foundGeneID){
        foundGeneID <- toupper(input$genefinder) %in% toupper(rownames(values$mydst))
        if (foundGeneID) {
          return(paste0("Maybe you mis-spelled the name of your gene. Did you mean ",
                        unique(rownames(values$myannotation)[which(toupper(input$genefinder) == toupper(rownames(values$myannotation)))]), "?"))
        } else {
          foundGeneNAME <- input$genefinder %in% values$myannotation$gene_name
          if (!foundGeneNAME) {
            foundGeneNAME <- toupper(input$genefinder) %in% toupper(values$myannotation$gene_name)
            if (foundGeneNAME) {
              return(paste0("Maybe you mis-spelled the name of your gene. Did you mean ",
                            unique(values$myannotation$gene_name[which(toupper(input$genefinder) == toupper(values$myannotation$gene_name))]), "?"))
            } else {
              return("Could not find the gene you typed!")
            }
          } else {
            fgn <- values$myannotation$gene_name[which(values$myannotation$gene_name == input$genefinder)]
            if (length(fgn) > 1) return(paste0("Found more than one gene with the selected gene name. Select one of the following: ", paste(selectedGene, collapse = ", ")))
            selectedGene <- rownames(values$myannotation)[which(values$myannotation$gene_name == input$genefinder)]
            
            fg <- rownames(values$myannotation)[match(fgn, values$myannotation$gene_name)]
            return(paste0("I found the gene! Plotting ", fg, " - ", values$myannotation$gene_name[match(fg, rownames(values$myannotation))], "..."))
            
          }}
      } else {
        fg <- rownames(values$myannotation)[match(input$genefinder, rownames(values$mydst))]
        return(paste0("I found the gene! Plotting ", fg, " - ", values$myannotation$gene_name[match(fg, rownames(values$myannotation))], "..."))
        
      }
    })
    
    output$genefinder_plot <- renderPlot({
      anno_id <- rownames(values$mydst)
      anno_gene <- values$myannotation$gene_name
      
      if (is.null(input$color_by) & input$genefinder != "")
        return(ggplot() + annotate("text", label = "Select a factor to plot your gene", 0, 0) + theme_bw())
      if (is.null(input$color_by) & input$genefinder == "")
        return(ggplot() + annotate("text", label = "Select a gene and a factor to plot gene", 0, 0) + theme_bw())
      if (input$genefinder == "")
        return(ggplot() + annotate("text", label = "Type in a gene name/id", 0, 0) + theme_bw())
      if (!input$genefinder %in% anno_gene & !input$genefinder %in% anno_id)
        return(ggplot() + annotate("text", label = "Gene not found...", 0, 0) + theme_bw())
      
      if (input$genefinder %in% anno_id) {
        selectedGene <- rownames(values$mydst)[match(input$genefinder, rownames(values$mydst))]
        selectedGeneSymbol <- values$myannotation$gene_name[match(selectedGene, rownames(values$myannotation))]
      }
      if (input$genefinder %in% anno_gene) {
        selectedGeneSymbol <- values$myannotation$gene_name[which(values$myannotation$gene_name == input$genefinder)]
        if (length(selectedGeneSymbol) > 1) return(ggplot() + annotate("text", label = paste0("Type in a gene name/id of the following:\n", paste(selectedGene, collapse = ", ")), 0, 0) + theme_bw())
        selectedGene <- rownames(values$myannotation)[which(values$myannotation$gene_name == input$genefinder)]
      }
      genedata <- plotCounts(values$mydds, gene = selectedGene, intgroup = input$color_by, returnData = TRUE)
      onlyfactors <- genedata[, match(input$color_by, colnames(genedata))]
      genedata$plotby <- interaction(onlyfactors)
      genedata$sampleID <- rownames(genedata)
      
      # input$plot_style chooses the style of plotting
      if (input$plot_style == "boxplot") {
        res <- ggplot(genedata, aes_string(x = "plotby", y = "count", fill = "plotby")) +
          geom_boxplot(outlier.shape = NA, alpha = 0.7) + theme_bw()
        if (input$ylimZero) {
          res <- res + scale_y_log10(name = "Normalized counts - log10 scale", limits = c(0.4, NA))
        } else {
          res <- res + scale_y_log10(name = "Normalized counts - log10 scale")
        }
        
        res <- res +
          labs(title = paste0("Normalized counts for ", selectedGeneSymbol, " - ", selectedGene)) +
          scale_x_discrete(name = "") +
          geom_jitter(aes_string(x = "plotby", y = "count"), position = position_jitter(width = 0.1)) +
          scale_fill_discrete(name = "Experimental\nconditions")
        if (input$addsamplelabels) {
          res <- res + geom_text(aes_string(label = "sampleID"), hjust = -.1, vjust = 0)
        }
        exportPlots$genefinder_countsplot <- res
        res
      } else if (input$plot_style == "violin plot") {
        res <- ggplot(genedata, aes_string(x = "plotby", y = "count", fill = "plotby")) +
          geom_violin(aes_string(col = "plotby"), alpha = 0.6) + theme_bw()
        if (input$ylimZero) {
          res <- res + scale_y_log10(name = "Normalized counts - log10 scale", limits = c(0.4, NA))
        } else {
          res <- res + scale_y_log10(name = "Normalized counts - log10 scale")
        }
        
        res <- res +
          labs(title = paste0("Normalized counts for ", selectedGeneSymbol, " - ", selectedGene)) +
          scale_x_discrete(name = "") +
          geom_jitter(aes_string(x = "plotby", y = "count"), alpha = 0.8, position = position_jitter(width = 0.1)) +
          scale_fill_discrete(name = "Experimental\nconditions") + scale_color_discrete(guide = "none")
        if (input$addsamplelabels) {
          res <- res + geom_text(aes_string(label = "sampleID"), hjust = -.1, vjust = 0)
        }
        exportPlots$genefinder_countsplot <- res
        res
      }
    })
    
    output$genefinder_table <- DT::renderDataTable({
      anno_id <- rownames(values$mydst)
      anno_gene <- values$myannotation$gene_name
      
      if (is.null(input$color_by) & input$genefinder != "")
        return(NULL)
      if (is.null(input$color_by) & input$genefinder == "")
        return(NULL)
      if (input$genefinder == "")
        return(NULL)
      if (!input$genefinder %in% anno_gene & !input$genefinder %in% anno_id)
        return(NULL)
      
      if (input$genefinder %in% anno_id) {
        selectedGene <- rownames(values$mydst)[match(input$genefinder, rownames(values$mydst))]
        selectedGeneSymbol <- values$myannotation$gene_name[match(selectedGene, rownames(values$myannotation))]
      }
      if (input$genefinder %in% anno_gene) {
        selectedGeneSymbol <- values$myannotation$gene_name[which(values$myannotation$gene_name == input$genefinder)]
        if (length(selectedGeneSymbol) > 1) return(ggplot() + annotate("text", label = paste0("Type in a gene name/id of the following:\n", paste(selectedGene, collapse = ", ")), 0, 0) + theme_bw())
        selectedGene <- rownames(values$myannotation)[which(values$myannotation$gene_name == input$genefinder)]
      }
      genedata <- plotCounts(values$mydds, gene = selectedGene, intgroup = input$color_by, returnData = TRUE)
      genedata
    })
    
    # server pca2go ---------------------------------------------------------------
    output$ui_computePCA2GO <- renderUI({
      if (is.null(pca2go))
        actionButton("computepca2go", "Compute the PCA2GO object", icon = icon("spinner"), class = "btn btn-primary")
    })
    
    annoSpecies_df <- data.frame(
      species = c("", "Anopheles", "Arabidopsis", "Bovine", "Worm",
                  "Canine", "Fly", "Zebrafish", "E coli strain K12",
                  "E coli strain Sakai", "Chicken", "Human", "Mouse",
                  "Rhesus", "Malaria", "Chimp", "Rat",
                  "Yeast", "Streptomyces coelicolor", "Pig", "Toxoplasma gondii",
                  "Xenopus"),
      pkg = c("", "org.Ag.eg.db", "org.At.tair.db", "org.Bt.eg.db", "org.Ce.eg.db",
              "org.Cf.eg.db", "org.Dm.eg.db", "org.Dr.eg.db", "org.EcK12.eg.db",
              "org.EcSakai.eg.db", "org.Gg.eg.db", "org.Hs.eg.db", "org.Mm.eg.db",
              "org.Mmu.eg.db", "org.Pf.plasmo.db", "org.Pt.eg.db", "org.Rn.eg.db",
              "org.Sc.sgd.db", "org.Sco.eg.db", "org.Ss.eg.db", "org.Tgondii.eg.db",
              "org.Xl.eg.db"),
      stringsAsFactors = FALSE)
    annoSpecies_df <- annoSpecies_df[order(annoSpecies_df$species), ]
    annoSpecies_df <- annoSpecies_df[annoSpecies_df$species %in% c("", "Human", "Mouse", "Rat", "Fly", "Chimp"), ]
    
    output$ui_selectspecies <- renderUI({
      if (is.null(values$mypca2go)) {
        selectInput("speciesSelect", label = "Select the species of your samples", choices = annoSpecies_df$species, selected = "")
      }
    })
    output$ui_inputtype <- renderUI({
      if (is.null(values$mypca2go)) {
        selectInput("idtype", label = "Select the input type of your identifiers",
                    choices = c("ENSEMBL", "SYMBOL", "REFSEQ", "ENTREZID"), selected = "ENSEMBL")
      }
    })
    
    output$speciespkg <- renderText({
      if (!is.null(pca2go))
        return("pca2go object provided")
      if (!is.null(values$mypca2go))
        return("pca2go object computed or provided")
      shiny::validate(
        need(input$speciesSelect != "",
             "Select a species - requires the corresponding annotation package"
        )
      )
      annopkg <- annoSpecies_df$pkg[annoSpecies_df$species == input$speciesSelect]
      shiny::validate(
        need(require(annopkg, character.only = TRUE),
             paste0("The package ", annopkg, " is not installed/available. Try installing it with BiocManager::install('", annopkg, "')"))
      )
      
      retmsg <- paste0(annopkg, " - package available and loaded")
      # if (!require(annopkg,character.only=TRUE)) {
      # stop("The package",annopkg, "is not installed/available. Try installing it with BiocManager::install() ?")
      # }
      retmsg <- paste0(retmsg, " - ", gsub(".eg.db", "", gsub("org.", "", annopkg)))
      retmsg
    })
    
    computedPCA2GO <- eventReactive(input$computepca2go, {
      annopkg <- annoSpecies_df$pkg[annoSpecies_df$species == input$speciesSelect]
      withProgress(
        message = "Computing the PCA2GO object...",
        detail = "This operation can take a while.",
        value = 0,
        {
          pcpc <- limmaquickpca2go(values$mydst, background_genes = rownames(values$mydds),
                                   inputType = input$idtype,
                                   organism = gsub(".eg.db", "", gsub("org.", "", annopkg)))
        })
      pcpc
    })
    
    observeEvent(input$computepca2go,
                 {
                   values$mypca2go <- computedPCA2GO()
                 })
    
    output$pca2go <- renderPlot({
      shiny::validate(
        need(
          !is.null(values$mypca2go),
          "Please provide a pca2go object to the app or alternatively click on the action button - could take some time to compute live!"
        )
      )
      res <- 
        pcaplot(
          values$mydst, intgroup = input$color_by,
          ntop = attr(values$mypca2go, "n_genesforpca"),
          pcX = as.integer(input$pc_x), pcY = as.integer(input$pc_y),
          text_labels = input$sample_labels,
          point_size = input$pca_point_size, 
          title = paste0(
            "PCA on the samples - ", attr(values$mypca2go, "n_genesforpca"), " genes used"
          ),
          ellipse = input$pca_ellipse, ellipse.prob = input$pca_cislider
        )
      res
    })
    
    output$dt_pchor_pos <- DT::renderDataTable({
      if (is.null(values$mypca2go)) return(datatable(NULL))
      goe <- values$mypca2go[[paste0("PC", input$pc_x)]][["posLoad"]]
      if(input$compact_pca2go)
        return(datatable(goe[, c("GO.ID", "Term", "Significant", "p.value_elim")], options = list(pageLength = 5)))
      datatable(goe)
    })
    
    output$dt_pchor_neg <- DT::renderDataTable({
      if (is.null(values$mypca2go)) return(datatable(NULL))
      goe <- values$mypca2go[[paste0("PC", input$pc_x)]][["negLoad"]]
      if (input$compact_pca2go)
        return(datatable(goe[, c("GO.ID", "Term", "Significant", "p.value_elim")], options = list(pageLength = 5)))
      datatable(goe)
    })
    
    output$dt_pcver_pos <- DT::renderDataTable({
      if (is.null(values$mypca2go)) return(datatable(NULL))
      goe <- values$mypca2go[[paste0("PC", input$pc_y)]][["posLoad"]]
      if (input$compact_pca2go)
        return(datatable(goe[, c("GO.ID", "Term", "Significant", "p.value_elim")], options = list(pageLength = 5)))
      datatable(goe)
    })
    
    output$dt_pcver_neg <- DT::renderDataTable({
      if (is.null(values$mypca2go)) return(datatable(NULL))
      goe <- values$mypca2go[[paste0("PC", input$pc_y)]][["negLoad"]]
      if (input$compact_pca2go)
        return(datatable(goe[, c("GO.ID", "Term", "Significant", "p.value_elim")], options = list(pageLength = 5)))
      datatable(goe)
    })
    
    output$enrichinfo <- renderPrint({
      cat("enrich info:\n")
      # str(goEnrichs)
      class(input$pc_x)
      head(values$mypca2go[[paste0("PC", input$pc_x)]][["posLoad"]])
      class(datatable(values$mypca2go[[paste0("PC", input$pc_x)]][["posLoad"]]))
    })
    
    # server multifactor exploration ----------------------------------------------------------
    output$intro_multifac <- renderText({
      if (!is.null(values$mydds))
        shiny::validate(
          need(ncol(colData(values$mydds)) > 1,
               message = "To use this section, you need a dataset where more than one experimental factor is available.")
        )
      return("Refer to the Instructions section if you need help on using this section")
    })
    
    output$covar1 <- renderUI({
      # if(is.null(values$mydst))
      # return(NULL)
      poss_covars <- names(colData(values$mydds))
      selectInput("covar1", label = "Select factor 1: ",
                  choices = c(NULL, poss_covars), selected = NULL, multiple = FALSE)
    })
    
    output$covar2 <- renderUI({
      # if(is.null(values$mydst))
      # return(NULL)
      poss_covars <- names(colData(values$mydds))
      selectInput("covar2", label = "Select factor 2: ",
                  choices = c(NULL, poss_covars), selected = NULL, multiple = FALSE)
    })
    
    output$c1levels <- renderUI({
      if (is.null(input$covar1))
        return(NULL)
      fac1lev <- levels(colData(values$mydst)[[input$covar1]])
      selectInput("covar1levels", label = "Factor 1 available levels: ",
                  choices = c(NULL, fac1lev), selected = NULL, multiple = TRUE) # actually 2
    })
    
    output$c2levels <- renderUI({
      if (is.null(input$covar2))
        return(NULL)
      fac2lev <- levels(colData(values$mydst)[[input$covar2]])
      selectInput("covar2levels", label = "Factor 2 available levels: ",
                  choices = c(NULL, fac2lev), selected = NULL, multiple = TRUE) # 2 or more are allowed!
    })
    
    output$colnames1 <- renderUI({
      if (is.null(values$mydst))
        return(NULL)
      if (is.null(input$covar1))
        return(NULL)
      if (is.null(input$covar2))
        return(NULL)
      
      fac1 <- input$covar1
      fac2 <- input$covar2
      
      fac1_touse <- input$covar1levels
      fac2_touse <- input$covar2levels
      
      preselected_fac1 <- colnames(values$mydst)[colData(values$mydst)[[fac1]] %in% fac1_touse]
      preselected_fac2 <- colnames(values$mydst)[colData(values$mydst)[[fac2]] %in% fac2_touse]
      presel <- intersect(preselected_fac1, preselected_fac2)
      mysamples <- colData(values$mydst)[presel, ] # check that the repl are balanced
      
      presel1 <- colnames(values$mydst)[(colData(values$mydst)[[fac1]] %in% fac1_touse[1]) & colData(values$mydst)[[fac2]] %in% fac2_touse]
      
      selectInput(
        "picksamples1", label = "Combine samples from Factor1-Level1 in the selected order: ",
        choices = c(NULL, presel1), selected = NULL, multiple = TRUE)
    })
    
    output$colnames2 <- renderUI({
      if (is.null(values$mydst))
        return(NULL)
      if (is.null(input$covar1))
        return(NULL)
      if (is.null(input$covar2))
        return(NULL)
      
      fac1 <- input$covar1
      fac2 <- input$covar2
      
      fac1_touse <- input$covar1levels
      fac2_touse <- input$covar2levels
      
      preselected_fac1 <- colnames(values$mydst)[colData(values$mydst)[[fac1]] %in% fac1_touse]
      preselected_fac2 <- colnames(values$mydst)[colData(values$mydst)[[fac2]] %in% fac2_touse]
      presel <- intersect(preselected_fac1, preselected_fac2)
      mysamples <- colData(values$mydst)[presel, ] # check that the repl are balanced
      
      presel2 <- colnames(values$mydst)[(colData(values$mydst)[[fac1]] %in% fac1_touse[2]) & colData(values$mydst)[[fac2]] %in% fac2_touse]
      selectInput("picksamples2", label = "Combine samples from Factor1-Level2 in the selected order: ",
                  choices = c(NULL, presel2), selected = NULL, multiple = TRUE)
    })
    
    composedMat <- eventReactive(input$composemat, {
      exprmat <- t(assay(values$mydst))
      exprmat <- exprmat[, rowSums(counts(values$mydds) > 5) > 2]
      
      withProgress(message = "Composing the matrix...",
                   value = 0,
                   {
                     pcmat <- cbind(exprmat[input$picksamples1, ],
                                    exprmat[input$picksamples2, ])
                   })
      pcmat
    })
    
    obj3 <- reactive({
      pcmat <- composedMat()
      aval <- 0.3
      fac2pal <- alpha(c("green", "red", "blue", "orange", "violet"), aval) # 5 are enough
      # colData(values$mydst)[input$covar2][rownames(pcmat),]
      max.type <- apply(pcmat[, 1:(ncol(pcmat)/2)], 2, which.max)
      
      fac2_col <- factor(colData(values$mydst)[input$covar2][rownames(pcmat), ],
                         levels = unique(as.character(colData(values$mydst)[input$covar2][rownames(pcmat), ])))
      tcol.justMax <- fac2pal[fac2_col][max.type]
      # tcol.justMax <- ifelse(max.type <= 4,"green",ifelse(max.type <= 8,"red",ifelse(max.type <= 12,"blue","orange")))
      
      max.type2 <- apply(pcmat[, ((ncol(pcmat) / 2) + 1):ncol(pcmat)], 2, which.max)
      # tcol2.justMax <- ifelse(max.type2 <= 4,alpha("green",aval),ifelse(max.type2 <= 8,alpha("red",aval),ifelse(max.type2 <= 12,alpha("blue",aval),alpha("orange",aval))))
      
      tcol2.justMax <- fac2pal[fac2_col][max.type2]
      
      # using the median across replicates
      celltypes <- gsub("_R.", "", rownames(pcmat))
      
      tcol <- tcol.justMax
      tcol2 <- tcol2.justMax
      # pcmat
      return(list(pcmat, tcol, tcol2))
    })
    
    output$pcamultifac <- renderPlot({
      pcmat <- obj3()[[1]]
      tcol <- obj3()[[2]]
      tcol2 <- obj3()[[3]]
      pres <- prcomp(t(pcmat), scale=FALSE)
      
      plot.index <- c(as.integer(input$pc_x_multifac), as.integer(input$pc_y_multifac))
      offset <- ncol(pcmat) / 2
      gene.no <- offset
      pcx <- pres$x
      # set.seed(11)
      # for (i in 1:ncol(pcx)) {
      #   pcx[,i] <- pcx[,i] + rnorm(nrow(pcx),sd=diff(range(pcx[,i]))/100)
      # }
      plot(pcx[(offset + 1):ncol(pcmat), plot.index[1]][1:gene.no], 
           pcx[(offset + 1):ncol(pcmat), plot.index[2]][1:gene.no], xlim = range(pcx[, plot.index[1]]), ylim = range(pcx[, plot.index[2]]), pch = 20, col = tcol, cex = 0.3)#,type="n")
      #plot(0,type="n",xlim=range(pres$x[,plot.index]),ylim=range(pres$x[,plot.index]))
      lcol <- ifelse(tcol != tcol2, "black", "grey")
      for (i in 1:gene.no) {
        lines(pcx[c(i, offset + i), plot.index[1]], pcx[c(i, offset + i), plot.index[2]], col = lcol[i])
      }
      points(pcx[1:offset, plot.index[1]][1:gene.no], pcx[1:offset, plot.index[2]][1:gene.no], pch = 20, col = tcol, cex = 0.3)
      points(pcx[(offset + 1):ncol(pcmat), plot.index[1]][1:gene.no], pcx[(offset + 1):ncol(pcmat), plot.index[2]][1:gene.no], pch = 20, col = tcol2, cex = 0.3)
    })
    
    output$multifaczoom <- renderPlot({
      if (is.null(input$pcamultifac_brush)) return(NULL)
      pcmat <- obj3()[[1]]
      tcol <- obj3()[[2]]
      tcol2 <- obj3()[[3]]
      pres <- prcomp(t(pcmat), scale = FALSE)
      
      plot.index <- c(as.integer(input$pc_x_multifac), as.integer(input$pc_y_multifac))
      offset <- ncol(pcmat) / 2
      gene.no <- offset
      pcx <- pres$x
      
      plot(pcx[(offset + 1):ncol(pcmat), plot.index[1]][1:gene.no],
           pcx[(offset + 1):ncol(pcmat), plot.index[2]][1:gene.no],
           xlim = c(input$pcamultifac_brush$xmin, input$pcamultifac_brush$xmax),
           ylim = c(input$pcamultifac_brush$ymin, input$pcamultifac_brush$ymax),
           pch = 20, col = tcol, cex = 0.3)#,type="n")
      #plot(0,type="n",xlim=range(pres$x[,plot.index]),ylim=range(pres$x[,plot.index]))
      lcol <- ifelse(tcol != tcol2, "black", "grey")
      for (i in 1:gene.no) {
        lines(pcx[c(i, offset + i), plot.index[1]], pcx[c(i, offset + i), plot.index[2]], col = lcol[i])
      }
      points(pcx[1:offset, plot.index[1]][1:gene.no], pcx[1:offset, plot.index[2]][1:gene.no], pch = 20, col = tcol, cex = 0.3)
      points(pcx[(offset + 1):ncol(pcmat), plot.index[1]][1:gene.no], pcx[(offset + 1):ncol(pcmat),plot.index[2]][1:gene.no], pch = 20, col = tcol2, cex = 0.3)
      
    })
    
    curData_brush_multifac <- reactive({
      pcmat <- obj3()[[1]]
      tcol <- obj3()[[2]]
      tcol2 <- obj3()[[3]]
      
      pres <- prcomp(t(pcmat), scale = FALSE)
      
      plot.index <- c(as.integer(input$pc_x_multifac), as.integer(input$pc_y_multifac))
      offset <- ncol(pcmat) / 2
      gene.no <- offset
      pcx <- pres$x
      
      firstPCselected <- c(
        pcx[1:offset, plot.index[1]][1:gene.no],
        pcx[(offset + 1):ncol(pcmat), plot.index[1]][1:gene.no])
      
      secondPCselected <- c(
        pcx[1:offset, plot.index[2]][1:gene.no],
        pcx[(offset + 1):ncol(pcmat), plot.index[2]][1:gene.no])
      
      pcspcs <- data.frame(firstPC = firstPCselected, secondPC = secondPCselected, geneID = colnames(pcmat))
      rownames(pcspcs) <- c(paste0(colnames(pcmat)[1:gene.no], "_WT"),
                            paste0(colnames(pcmat)[(gene.no + 1) : (2 * gene.no)], "_G37"))
      
      if (!is.null(values$myannotation))
        pcspcs$geneName <- values$myannotation$gene_name[match(pcspcs$geneID, rownames(values$myannotation))]
      
      res <- brushedPoints(pcspcs, input$pcamultifac_brush, xvar = "firstPC", yvar = "secondPC")
      res
    })
    
    output$pcamultifac_out <- DT::renderDataTable({
      datatable(curData_brush_multifac())
    })
    
    output$downloadData_brush_multifac <- downloadHandler(
      filename = function() { paste(input$brushedPoints_filename_multifac, ".csv", sep = "") },
      content = function(file) {
        if (length(input$pcamultifac_out_rows_selected)){
          data <- curData_brush_multifac()[input$pcamultifac_out_rows_selected, ]
        } else {
          data <- curData_brush_multifac()
        }
        write.csv(data, file, quote = FALSE)
      }
    )
    
    # server report editor ---------------------------------------------------------
    ### yaml generation
    rmd_yaml <- reactive({
      paste0("---",
             "\ntitle: '", input$report_title,
             "'\nauthor: '", input$report_author,
             "'\ndate: '", Sys.Date(),
             "'\noutput:\n  html_document:\n    toc: ", input$report_toc, "\n    number_sections: ", input$report_ns, "\n    theme: ", input$report_theme, "\n---\n\n", collapse = "\n")
    })
    
    # rmd_full <- reactive({
    #   paste0(rmd_yaml(),"\n",
    #          readLines("reportTemplate.Rmd"))
    # })
    # output$loadedRmd <- renderPrint({
    #   # rmd_yaml() # or rmd_full()
    #   paste0(
    #     # rmd_yaml(),
    #     paste0(readLines("reportTemplate.Rmd"),collapse = "\n"))
    #   # head(paste0(rmd_yaml(),
    #   # readLines("reportTemplate.Rmd")),collapse="\n")
    # })
    
    ### loading report template
    # update aceEditor module
    observe({
      # loading rmd report from disk
      inFile <- system.file("extdata", "reportTemplate.Rmd", package = "pcaExplorer")
      isolate({
        if (!is.null(inFile) && !is.na(inFile)) {
          
          rmdfilecontent <- paste0(readLines(inFile), collapse = "\n")
          
          shinyAce::updateAceEditor(session, "acereport_rmd", value = rmdfilecontent)
        }
      })
    })
    
    ### ace editor options
    observe({
      autoComplete <- if (input$enableAutocomplete) {
        if (input$enableLiveCompletion) "live" else "enabled"
      } else {
        "disabled"
      }
      updateAceEditor(session, "acereport_rmd", autoComplete = autoComplete, theme = input$theme, mode = input$mode)
      # updateAceEditor(session, "plot", autoComplete = autoComplete)
    })
    
    #Enable/Disable R code completion
    rmdOb <- aceAutocomplete("acereport_rmd")
    observe({
      if (input$enableRCompletion) {
        rmdOb$resume()
      } else {
        rmdOb$suspend()
      }
    })
    
    ## currently not working as I want with rmarkdown::render, but can leave it like this - the yaml will be taken in the final version only
    output$knitDoc <- renderUI({
      input$updatepreview_button
      return(
        withProgress(
          message = "Updating the report in the app body",
          detail = "This can take some time",
          {
            # temporarily switch to the temp dir, in case you do not have write
            # permission to the current working directory
            owd <- setwd(tempdir())
            on.exit(setwd(owd))
            tmp_content <- paste0(rmd_yaml(), input$acereport_rmd, collapse = "\n")
            incProgress(0.5, detail = "Rendering report...")
            htmlpreview <- knit2html(text = tmp_content, fragment.only = TRUE, quiet = TRUE)
            incProgress(1)
            isolate(HTML(htmlpreview))
          })
      )
    })
    
    
    # server state saver ---------------------------------------------------------
    ### to environment
    observe({
      if (is.null(input$exit_and_save) || input$exit_and_save == 0) return()
      
      # quit R, unless you are running an interactive session
      if (interactive()) {
        # flush input and values to the environment in two distinct objects (to be reused later?)
        isolate({
          
          # pcaexplorer_env <<- new.env(parent = emptyenv())
          cur_inputs <- reactiveValuesToList(input)
          cur_values <- reactiveValuesToList(values)
          tstamp <- gsub(" ", "_", gsub("-", "", gsub(":", "-", as.character(Sys.time()))))
          
          # better practice rather than assigning to global env - notify users of this
          assign(paste0("pcaExplorer_inputs_", tstamp), cur_inputs, envir = pcaexplorer_env)
          assign(paste0("pcaExplorer_values_", tstamp), cur_values, envir = pcaexplorer_env)
          stopApp("pcaExplorer closed, state successfully saved to global R environment.")
        })
      } else {
        stopApp("pcaExplorer closed")
        q("no")
      }
    })
    
    ### to binary data
    saveState <- function(filename) {
      isolate({
        LiveInputs <- reactiveValuesToList(input)
        # values[names(LiveInputs)] <- LiveInputs
        r_data <- reactiveValuesToList(values)
        save(LiveInputs, r_data, file = filename)
      })
    }
    
    output$state_save_sc <- downloadHandler(
      filename = function() {
        paste0("pcaExplorerState_", gsub(" ", "_", gsub("-", "", gsub(":", "-", as.character(Sys.time())))), ".RData")
      },
      content = function(file) {
        saveState(file)
      }
    )
    
    # server download handlers ---------------------------------------------------------
    output$downloadData_brush <- downloadHandler(
      filename = function() { paste(input$brushedPoints_filename, ".csv", sep = "") },
      content = function(file) {
        if (length(input$pca_brush_out_rows_selected)){
          data <- curData_brush()[input$pca_brush_out_rows_selected, ]
        } else {
          data <- curData_brush()
        }
        write.csv(data, file, quote = FALSE)
      }
    )
    
    output$downloadData_click <- downloadHandler(
      filename = function() { paste(input$clickedPoints_filename, ".csv", sep = "") },
      content = function(file) {
        write.csv(curData_click(), file, quote = FALSE)
      }
    )
    
    output$download_samplessamplesheat <- downloadHandler(filename = function() {
      input$filename_samplessamplesheat
    },
    content = function(file){
      pdf(file)
      
      if (!is.null(input$color_by)) {
        expgroups <- as.data.frame(colData(values$mydst)[, input$color_by])
        # expgroups <- interaction(expgroups)
        rownames(expgroups) <- colnames(values$mydst)
        colnames(expgroups) <- input$color_by
        
        pheatmap(as.matrix(dist(t(assay(values$mydst)))), annotation_col = expgroups)
      } else {
        pheatmap(as.matrix(dist(t(assay(values$mydst)))))
      }
      
      dev.off()
    })
    
    output$download_readsbarplot <- downloadHandler(
      filename = function() { input$filename_readsbarplot },
      content = function(file) {
        ggsave(file, exportPlots$reads_barplot, width = input$export_width, height = input$export_height, units = "cm")
      })
    
    output$download_samplesPca <- downloadHandler(
      filename = function() { input$filename_samplesPca },
      content = function(file) {
        ggsave(file, exportPlots$samplesPca, width = input$export_width, height = input$export_height, units = "cm")
      })
    
    output$download_samplesScree <- downloadHandler(
      filename = function() { input$filename_samplesScree },
      content = function(file) {
        ggsave(file, exportPlots$samplesScree, width = input$export_width, height = input$export_height, units = "cm")
      })
    
    output$download_samplesPcazoom <- downloadHandler(
      filename = function() { input$filename_samplesPcazoom },
      content = function(file) {
        ggsave(file, exportPlots$samplesZoom, width = input$export_width, height = input$export_height, units = "cm")
      })
    
    output$download_samplesPca_hiload <- downloadHandler(filename = function() {
      input$filename_samplesPca_hiload
    },
    content = function(file) {
      pdf(file)
      rv <- rowVars(assay(values$mydst))
      select <- order(rv, decreasing = TRUE)[seq_len(min(input$pca_nrgenes, length(rv)))]
      pca <- prcomp(t(assay(values$mydst)[select, ]))
      
      par(mfrow = c(2, 1))
      hi_loadings(pca, whichpc = as.integer(input$pc_x), topN = input$ntophiload, annotation = values$myannotation)
      hi_loadings(pca, whichpc = as.integer(input$pc_y), topN = input$ntophiload, annotation = values$myannotation)
      dev.off()
    })
    
    output$download_samplesPca_sampleout <- downloadHandler(
      filename = function() { input$filename_samplesPca_sampleout },
      content = function(file) {
        ggsave(file, exportPlots$samplesOutlier, width = input$export_width, height = input$export_height, units = "cm")
      })
    
    output$download_genesPca <- downloadHandler(
      filename = function() { input$filename_genesPca },
      content = function(file) {
        ggsave(file, exportPlots$genesPca, width = input$export_width, height = input$export_height, units = "cm")
      })
    
    output$download_genesZoom <- downloadHandler(
      filename = function() { input$filename_genesZoom },
      content = function(file) {
        ggsave(file, exportPlots$genesZoom, width = input$export_width, height = input$export_height, units = "cm")
      })
    
    output$download_genesPca_profile <- downloadHandler(
      filename = function() {
        input$filename_genesPca_profile
      },
      content = function(file) {
        pdf(file)
        geneprofiler(values$mydst,
                     genelist = curData_brush()$ids,
                     intgroup = input$color_by,
                     plotZ = input$zprofile)
        dev.off()
      })
    
    output$download_genesPca_countsplot <- downloadHandler(
      filename = function() { input$filename_genesPca_countsplot },
      content = function(file) {
        ggsave(file, exportPlots$genesBoxplot, width = input$export_width, height = input$export_height, units = "cm")
      })
    
    output$download_genesHeatmap <- downloadHandler(
      filename = function() {
        input$filename_genesHeatmap
      },
      content = function(file) {
        pdf(file)
        brushedObject <- curData_brush()
        selectedGenes <- brushedObject$ids
        toplot <- assay(values$mydst)[selectedGenes, ]
        rownames(toplot) <- values$myannotation$gene_name[match(rownames(toplot), rownames(values$myannotation))]
        aheatmap(toplot, Colv = as.logical(input$heatmap_colv))
        dev.off()
      })
    
    output$download_genefinder_countsplot <- downloadHandler(
      filename = function() { input$filename_genefinder_countsplot },
      content = function(file) {
        ggsave(file, exportPlots$genefinder_countsplot, width = input$export_width, height = input$export_height, units = "cm")
      })
    
    
    output$saveRmd <- downloadHandler(
      filename = function() {
        if (input$rmd_dl_format == "rmd") {
          "report.Rmd"
        } else {
          "report.html"
        }
      },
      content = function(file) {
        # knit2html(text = input$rmd, fragment.only = TRUE, quiet = TRUE))
        tmp_content <-
          paste0(rmd_yaml(),
                 input$acereport_rmd, collapse = "\n")
        # input$acereport_rmd
        if (input$rmd_dl_format == "rmd") {
          cat(tmp_content, file = file, sep = "\n")
        } else {
          # write it somewhere too keeping the source
          # tmpfile <- tempfile()
          # file.create(tmpfile)
          # fileConn<- file(tempfile())
          # writeLines(tmp_content, fileConn)
          # close(fileConn)
          if (input$rmd_dl_format == "html") {
            
            # temporarily switch to the temp dir, in case you do not have write
            # permission to the current working directory
            owd <- setwd(tempdir())
            on.exit(setwd(owd))
            
            cat(tmp_content, file = "tempreport.Rmd", sep = "\n")
            rmarkdown::render(input = "tempreport.Rmd",
                              output_file = file,
                              # fragment.only = TRUE,
                              quiet = TRUE)
          }
        }
      }
    )
  }) # end of pcaExplorer(dds,dst,countmatrix,coldata,pca2go,annotation)
  #nocov end
  shinyApp(ui = pcaexplorer_ui, server = pcaexplorer_server)
}

footer <- function() {
  tags$div(
    class = "footer",
    style = "text-align:center",
    tags$div(
      class = "foot-inner",
      list(
        hr(),
        "pcaExplorer is a project developed by Federico Marini in the Bioinformatics division of the ",
        tags$a(href = "http://www.unimedizin-mainz.de/imbei", "IMBEI"),
        ". ", br(),
        "Development of the pcaExplorer package is on ",
        tags$a(href = "https://github.com/federicomarini/pcaExplorer", "GitHub")
      )
    )
  )
}
